typescriptintermediate
Global Error Boundary Page
Handle uncaught errors gracefully with global-error.tsx including error logging and recovery.
typescriptPress ⌘/Ctrl + Shift + C to copy
// app/global-error.tsx
'use client';
import { useEffect } from 'react';
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
useEffect(() => {
// Log to error tracking service
console.error('Global error:', error);
// Sentry.captureException(error);
}, [error]);
return (
<html>
<body className="bg-[#0a0a0a] text-white">
<main className="min-h-screen flex items-center justify-center px-4">
<div className="text-center max-w-lg">
<div className="text-6xl mb-4">⚠</div>
<h1 className="text-2xl font-bold mb-2">Something went wrong</h1>
<p className="text-gray-400 mb-6">
An unexpected error occurred. Our team has been notified.
</p>
{error.digest && (
<p className="text-gray-600 text-sm mb-4">
Error ID: {error.digest}
</p>
)}
<div className="flex gap-3 justify-center">
<button
onClick={reset}
className="px-6 py-3 bg-blue-600 text-white rounded-lg
hover:bg-blue-500 transition-colors font-medium"
>
Try Again
</button>
<a
href="/"
className="px-6 py-3 bg-[#111] border border-white/10 rounded-lg
text-gray-300 hover:text-white hover:border-white/20
transition-colors font-medium"
>
Go Home
</a>
</div>
</div>
</main>
</body>
</html>
);
}
// app/[category]/error.tsx (segment-level error boundary)
// 'use client';
// export default function CategoryError({ error, reset }: { error: Error; reset: () => void }) {
// return (
// <div className="p-8 text-center">
// <h2 className="text-xl font-bold text-white">Failed to load category</h2>
// <p className="text-gray-400 mt-2">{error.message}</p>
// <button onClick={reset} className="mt-4 px-4 py-2 bg-blue-600 rounded-lg text-white">
// Retry
// </button>
// </div>
// );
// }Use Cases
- Production error recovery
- Error logging integration
- Graceful failure handling
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
typescriptbeginner
Custom Not Found Page
Create a custom not-found.tsx with search suggestions, popular links, and a return home button.
Best for: Custom 404 error pages
#nextjs#error
typescriptintermediate
Type-Safe API Route Handler
Next.js App Router route handler with input validation, typed responses, and proper error handling.
Best for: CRUD API endpoints
#api#route-handler
typescriptintermediate
Authentication Middleware Guard
Next.js middleware that checks auth tokens on protected routes and redirects unauthenticated users to login.
Best for: Dashboard access control
#middleware#authentication
typescriptintermediate
Server Action with Form Validation
Next.js Server Action handling form submissions with validation, error messages, and redirect on success.
Best for: Blog post creation
#server-actions#forms