Error boundaries
An error.tsx file creates a React error boundary for a route segment. It
catches unexpected errors thrown while rendering its children and shows a
fallback UI instead of crashing the app.
Because error boundaries must be Client Components, the file starts with
'use client' and receives error and a recovery function:
'use client';
export default function Error({ error, retry }: { error: unknown; retry: () => void }) {
return (
<div>
<h2>Something went wrong!</h2>
<button onClick={() => retry()}>Try again</button>
</div>
);
}
retry() re-fetches and re-renders the segment; reset() clears the error state
without re-fetching. Errors bubble to the nearest error.tsx, so you can place
them at different levels. Error boundaries do not catch errors in event
handlers or async code.
To handle errors in the root layout, add global-error.tsx, which must render
its own <html> and <body>. For component-level recovery anywhere in the tree,
catchError from next/error wraps any component in an error boundary.
In short: error.tsx is a Client Component boundary that receives the error and
a way to recover.
You are about to answer a short quiz on error.tsx / catchError.