Skip to main content

Global Error Handling

There are two pages for global error handling

  • Root level error.tsx. This file will handle errors on any component in the subtree through an error boundary. It does not catch any error in root level layout.tsx and page.tsx.
  • Root level global-error.tsx. It behaves as its own standalone page (need its own html and body tags) and it is displayed as fallback when an error occurs in layout.tsx or page.tsx.

Next.js documentation: source

How to validate it

NOTICE: File global-error.tsx can only be tested in a production build. You need to run the app with pnpm run build && pnpm run start.

NOTE: An utility component called Error was added to help testing this feature. You can find it under src/dev-utils/components/Error.

  1. Add the Error component in the component tree where you want to trigger the error.
  2. Run the app locally.
  3. You'll see a button Throw Error being rendered by the Error component. If you press the button, it will cause an error in next.js causing it to show an error handler screen.
  • Using the Error component in the root layout.tsx or root page.tsx will cause to display global-error.tsx if you are running a production build.
  • Using the Error component anywhere else in the subtree will cause an error that will call root level error.tsx (only if not caught by a more specific error.tsx in the subtree).

Screenshots

Page error.tsx image

Page global-error.tsx image

Recording