Nextjs Fundamentals · Optimization & Metadata

Error boundaries

`error.tsx` / `catchError`

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.

  1. An error.tsx file must be a Client Component, so it starts with 'use client'.
  2. An error boundary receives the thrown error and a ___ function that re-fetches and re-renders the segment.
  3. Error boundaries catch errors thrown inside event handlers.
  4. To handle errors in the root layout, add an ___ file that renders its own html and body.
  5. The ___ function from next/error wraps any component in an error boundary.