Error Handling & error.tsx
error.tsx file placed alongside page.tsx.error.tsx instead of letting the error bubble up and take down the rest of the page.app/dashboard/error.tsx
'use client'
import { useEffect } from 'react'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
// Log the error to an error reporting service
console.error(error)
}, [error])
return (
<div>
<h2>Something went wrong!</h2>
<button type="button" onClick={() => reset()}>
Try again
</button>
</div>
)
}error.tsx must be a Client Component — it needs the 'use client' directive at the top. Error boundaries are a React feature built on class component lifecycle methods under the hood, and that mechanism only works on the client. Forgetting the directive is one of the most common mistakes when adding error handling.The error and reset arguments
error.tsx component two props automatically — you never wire these up yourself.Prop | Description |
|---|---|
error | The Error instance that was thrown, optionally carrying a |
reset | A function that attempts to re-render the segment — useful when the error might be transient (e.g. a flaky network request) |
reset() doesn't reload the page. It simply tries to re-render the error boundary's children, which gives the user a lightweight "try again" experience instead of a full page refresh.Errors are scoped to the segment
error.tsx inside a specific route folder means only errors thrown within that segment — and its children — are caught there. An error thrown in app/dashboard/settings/ is caught by a error.tsx in that folder if one exists, or bubbles up to the nearest ancestor segment that has one. This lets you isolate a crash to a small part of the UI (say, a widget) while the rest of the page — navigation, sidebar, header — keeps working.Folder structure
app/
dashboard/
layout.tsx
error.tsx ← catches errors in page.tsx and settings/
page.tsx
settings/
page.tsxerror.tsx file does not catch errors thrown in its own segment's layout.tsx — the error boundary wraps the layout's children, not the layout itself. To catch an error thrown inside a layout, the error.tsx needs to live one level up, in the parent segment.try/catch in an event handler won't reach error.tsx — you handle those manually (for example by setting local state to show a message).error.tsxwraps a route segment in a React Error Boundary and must be a Client Component ('use client').It receives
error(the thrown Error, plus an optionaldigest) andreset(a function that re-renders the segment).Errors bubble up to the nearest ancestor
error.tsxif the segment where they occurred has none.A layout's own errors are not caught by that layout's sibling
error.tsx— only by one in a parent segment.