Error Handling
Next.js provides file conventions for handling errors automatically.
error.tsx
From app/dashboard/[slug]/error.tsx:
'use client';
export default function PostError({ error, reset }) {
return (
<div>
<h2>Something went wrong!</h2>
<p>{error.message}</p>
<button onClick={reset}>Try again</button>
</div>
);
}Error boundaries must be Client Components. The reset function re-renders the boundary's contents.
not-found.tsx
From app/dashboard/[slug]/not-found.tsx:
export default function PostNotFound() {
return (
<div>
<h2>Post Not Found</h2>
<Link href="/dashboard">Back to posts</Link>
</div>
);
}Trigger it with notFound() in queries:
const post = await prisma.post.findUnique({ where: { slug } });
if (!post) notFound();Errors bubble up to the nearest boundary. Create error.tsx at different route levels for granular handling.