Topic 35 of 47
error.js
Overview
The `error.tsx` file creates a React Error Boundary that catches unexpected runtime errors occurring in Server or Client Components within its route segment. It isolates the crash to the specific segment, keeping the rest of the app functional.
Syntax
tsx
// app/dashboard/error.tsx
'use client'; // Error components must be Client Components
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 in the Dashboard!</h2>
<button onClick={() => reset()}>Try again</button>
</div>
);
}Common Pitfalls
- `error.tsx` MUST be a Client Component (`'use client'`). Server Component errors are passed to it securely.
- To catch errors in the Root Layout (`app/layout.tsx`), you must use a special file named `global-error.tsx`.
Real-World Example
Error boundary hierarchies:
example
tsx
// Errors bubble up to the nearest error boundary.
app/
├── error.tsx // Catches any unhandled errors in the app
├── layout.tsx
└── dashboard/
├── error.tsx // Catches errors ONLY in the dashboard
├── layout.tsx
└── page.tsx // If this throws, dashboard/error.tsx handles it
// IMPORTANT: An error.tsx boundary DOES NOT catch errors thrown in its sibling layout.tsx.
// It only catches errors in its children (page.tsx or nested layouts).