Error Handling
Implement robust error handling to provide a better user experience and make debugging easier.
Important
Proper error handling is crucial for a production application. It helps users understand what went wrong and provides developers with valuable information for debugging.
Next.js Error Handling
Next.js 13+ provides built-in error handling with special files like
error.tsx
, not-found.tsx
, and global-error.tsx
.Custom 404 Not Found Page
Create a custom 404 page to provide a better user experience when visitors navigate to non-existent routes in your application.
File Location:
In Next.js 13+, you need to create a file named not-found.tsx
in your app directory.
TypeScript
// app/not-found.tsx import Link from 'next/link' import { Button } from '@/components/ui/button' export default function NotFound() { return ( <div className="flex flex-col items-center justify-center min-h-[70vh] px-4 text-center"> <h1 className="text-4xl font-bold tracking-tight text-foreground/90 mb-2">404</h1> <h2 className="text-2xl font-semibold text-foreground/80 mb-4">Page Not Found</h2> <p className="text-muted-foreground mb-8 max-w-md"> The page you are looking for doesn't exist or has been moved. </p> <Button asChild> <Link href="/">Return Home</Link> </Button> </div> ) }
Best Practices for Error Handling
- Always provide clear, user-friendly error messages
- Log errors for debugging but avoid exposing sensitive information to users
- Implement graceful fallbacks for different types of errors
- Use error boundaries to isolate errors and prevent the entire app from crashing
- Consider implementing a global error tracking service for production applications