Next.js Discord

Discord Forum

error handling (error.tsx, global-error.tsx)

Unanswered
Spectacled Caiman posted this in #help-forum
Open in Discord
Avatar
Spectacled CaimanOP
How does the error boundary (error.tsx / global-error.tsx) work? I had an error.tsx file in the app directory (/app/error.tsx) and in one of my client components, I threw an Error (like below) and it didn't render this error component. I'm just wondering, how can I actually render this error page?
// /app/profile/page.tsx

setTimeout(() => throw new Error('test'));

7 Replies

Avatar
Pembroke Welsh Corgi
The error boundary catches only the exceptions thrown by function components, therefore this exception will escape it since it happens in a separate function that is pushed to the call stack after the timeout is expired.

The same happens if you throw an error in an event handler, it will not get handled.

The React error boundary is a safe net only for errors that can break rendering.
Avatar
Spectacled CaimanOP
i dont think i understand, how can i test the error.tsx or global-error.tsx files? i've updated that setTimeout to this (below) but it doesnt render these files still, it just renders the red error notification in the bottom left and in prod it does nothing
new Promise((_, reject) => {
  setTimeout(() => {
    reject(new Error('test'));
  }, 2500);
});
Avatar
Selkirk Rex
In production, it does nothing because nothing should be exposed to hackers. Also, check the event loop to understand the above answer.
Avatar
Errors thrown during rendering of the component, such as
function Foo() {
  throw new Error(…)
  return <Bar />
}

are captured by error boundaries.

Errors thrown inside event handler or useEffect callbacks run separately from rendering. They do not crash the component and are not handled by the error boundary. You need to try/catch them.
In production error.tsx and global-error.tsx are still effective. In fact they do more things in prod mode than in dev mode where the default error overlay takes precedence.

In OP’s case it is just not a scenario where the error is handled by a boundary. OP can still open the browser console to see the error message in there.
Avatar
Selkirk Rex
I meant that when you deploy the application, sometimes errors occur that aren’t handled properly. Instead of the usual red error notification, you get a default white screen with a strange error code or hash in the middle. Only developers can use that code to identify the error. Or otherwise, as you mentioned, you can only see the details in the browser console.