Topic 16 of 39
Error Handling
Overview
The error.tsx file automatically isolates errors to specific route segments. If a page or layout crashes, Next.js displays this error UI instead of breaking the entire app, allowing the user to attempt recovery.
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
- Forgetting to add
'use client'at the top oferror.tsx. It will crash if it's a Server Component. - Expecting
error.tsxto catch errors thrown in thelayout.tsxof the SAME segment. It only catches errors in its children. To catch root layout errors, useglobal-error.tsx.
Interview Questions
Q:
Why must
error.tsx be a Client Component?A:
Errors can occur both on the server during rendering and on the client in the browser. A Client Component ensures it can catch and render UI for both environments, and it provides interactivity (like a reset() button) to recover.
Real-World Example
A graceful error fallback for a data-fetching component.
example
tsx
// When the DB fails, this isolates the crash to just this section
export default function ErrorBoundary({ error, reset }) {
return (
<div className="p-4 border border-red-500 bg-red-50 text-red-700">
<p>Failed to load data: {error.message}</p>
<button onClick={() => reset()} className="underline">Retry</button>
</div>
);
}Check Your Knowledge
Test your understanding of Error Handling with these quick questions.