How to handle error response in Next.js 13 Server Component? #50771
Replies: 4 comments 2 replies
-
|
+1 |
Beta Was this translation helpful? Give feedback.
-
|
+1 Hey @gidgudgod did you figure out an approach to handle this? |
Beta Was this translation helpful? Give feedback.
-
|
related to this #48681 (comment) |
Beta Was this translation helpful? Give feedback.
-
|
According to the docs when triggers a error on server component Next will look to nearest error file to render.
https://nextjs.org/docs/app/building-your-application/routing/error-handling You can use global-error.jsx (.tsx) to catch all errors 'use client';
export default function GlobalError({
error,
reset,
}: {
error: Error & { digest?: string };
reset: () => void;
}) {
return (
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
);
}Note: This not works in dev mode, remember to run your application in prod mode to verify this functionality. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
So I'm trying to fetch data that needs token header for authorization in Server Component
page.tsx. The data itself comes from external backend/API and it can response with different status code. IfUnauthorizedit will response with status401, ifNot Foundit will response with status404. Here I already provided a handle for each different error status:When it response with
404Next.js succeed showing the nearestnot-found.tsx. However the problem here is the401error, I don't know why Next.js won't delete the cookie as I already handle the401error response there. Instead deleting the cookie, Next.js just run thethrow new Error('Something went wrong!');right away which lead to showing the nearesterror.tsx. And then inerror.tsxcomponent, it shows the right error message in development build, but in production build it shows this different error message:error message in production build
Been searching and debugging for hours, yet still don't know why it won't handle the error.
Please is there any way to properly handle this different error status in Next.js 13 Server Component?
I need to at least delete the token cookies if it responses
401.Thanks.
Beta Was this translation helpful? Give feedback.
All reactions