typescriptintermediate
Error Handling with error.tsx and not-found.tsx
Handle errors gracefully with error.tsx boundaries and not-found.tsx pages in App Router.
typescriptPress ⌘/Ctrl + Shift + C to copy
// app/dashboard/error.tsx
'use client';
export default function DashboardError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return (
<div className="flex flex-col items-center justify-center min-h-[400px]">
<h2 className="text-xl font-bold mb-2">Something went wrong!</h2>
<p className="text-gray-500 mb-4">{error.message}</p>
<button
onClick={reset}
className="px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600"
>
Try again
</button>
</div>
);
}
// app/dashboard/not-found.tsx
import Link from 'next/link';
export default function DashboardNotFound() {
return (
<div className="flex flex-col items-center justify-center min-h-[400px]">
<h2 className="text-2xl font-bold mb-2">Not Found</h2>
<p className="text-gray-500 mb-4">Could not find the requested resource</p>
<Link href="/dashboard" className="text-blue-500 hover:underline">
Return to Dashboard
</Link>
</div>
);
}
// app/global-error.tsx (catches root layout errors)
'use client';
export default function GlobalError({
error,
reset,
}: {
error: Error;
reset: () => void;
}) {
return (
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={reset}>Try again</button>
</body>
</html>
);
}Use Cases
- error boundaries
- 404 pages
- graceful degradation
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptintermediate
Next.js Error Handling Patterns
Implement error.tsx, not-found.tsx, and global-error.tsx for comprehensive error handling.
Best for: Graceful error recovery in nested layouts
#nextjs#error-handling
typescriptbeginner
Redirect After Server Action
Use redirect() inside a server action to navigate after form submission in Next.js App Router.
Best for: form submissions
#nextjs#server-actions
typescriptintermediate
Catch-All and Optional Catch-All Routes
Handle dynamic nested routes with catch-all [...slug] and optional [[...slug]] segments.
Best for: documentation sites
#nextjs#routing
typescriptintermediate
Error Boundary with Fallback UI
Class-based error boundary component that catches render errors and displays a customizable fallback UI.
Best for: Graceful error recovery
#error-boundary#error-handling