Error handling
This page explains how to implement error boundaries and handle runtime errors effectively in Next.js.
error.tsx
Next.js provides error handling capabilities through a special error.tsx
file which automatically wraps route segments and their nested children in a React Error Boundary.
Directoryapp
Directoryblog
- page.tsx
- error.tsx
"use client";
export default function ErrorBoundary({ error }: { error: Error }) { return ( <div> <h2>Something went wrong!</h2> <p>{error.message}</p> </div> );}
Error boundaries must be client components (marked with “use client”) and receive the error object as a prop.
Testing error handling
Create a component that simulates random errors to test your error boundary:
export default function BlogPage() { const random = Math.random(); if (random > 0.5) { throw new Error("Failed to load blog"); }
return <h1>Product details</h1>;}
Without proper error handling, this results in:
- Development: An “Unhandled Runtime Error” with the error message
- Production: A generic “Application error: a client-side exception has occurred” message
With the error boundary in place, the error is caught and handled gracefully by showing the fallback UI.
Component hierarchy
Next.js processes route components in this order (top to bottom):
- Layout component
- Template component
- Error boundary (
error.tsx
) - Loading boundary (
loading.tsx
) - Not found boundary (
not-found.tsx
) - Page component
This ensures that errors are caught and handled by the appropriate boundaries, allowing for graceful fallback UI and error recovery.
Route segment error isolation
Error boundaries contain errors to specific route segments. For example:
"use client";
export default function ProductError({ error }: { error: Error }) { return ( <div> <h2>Error loading product</h2> <p>{error.message}</p> </div> );}
This error boundary only catches errors in the product route segment, leaving the rest of the application functional.
Good to know
- Error boundaries must be client components
- Errors are isolated to route segments
- Recovery is possible without full page reloads
- Error boundaries receive the error object as a prop
- The closest error boundary handles the error