javascript / intermediate
Snippet
Handling Global Errors in Next.js
The error.tsx file automatically catches errors in its segment and allows users to recover by re-rendering the component tree using the reset function.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'use client';export default function Error({error,reset,}: {error: Error & { digest?: string };reset: () => void;}) {return (<div><h2>Something went wrong!</h2><button onClick={() => reset()}>Try again</button></div>);}
nextjs
Breakdown
1
'use client';
Error boundaries must be Client Components.
2
reset: () => void
A function that attempts to re-render the segment to recover from the error.