Error handling in middleware
Answered
Cinnamon posted this in #help-forum
CinnamonOP
I'm using middleware to prevent unauthenticated requests. To do that it makes a request to check if session is authenticated.
I want to know how to handle error thrown while this request since the
Now it shows the error on the default error boundary
I want to know how to handle error thrown while this request since the
global-error.js didn't catch the error.// middleware.ts
try {
res = await fetch(`checktherequest`);
} catch (e) {
throw Error('Failed to check the request');
}
// global-error.tsx
'use client';
import React from 'react';
export default function GlobalError({ error, reset }: { error: Error; reset: () => void }) {
return (
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
);
}Now it shows the error on the default error boundary
Answered by joulev
Middleware is not part of the app router rendering process - there are no react components involved here so no error boundaries are triggered. You have to try/catch and ensure your middleware doesn’t throw
3 Replies
@Cinnamon I'm using middleware to prevent unauthenticated requests. To do that it makes a request to check if session is authenticated.
I want to know how to handle error thrown while this request since the `global-error.js` didn't catch the error.
typescript
// middleware.ts
try {
res = await fetch(`checktherequest`);
} catch (e) {
throw Error('Failed to check the request');
}
// global-error.tsx
'use client';
import React from 'react';
export default function GlobalError({ error, reset }: { error: Error; reset: () => void }) {
return (
<html>
<body>
<h2>Something went wrong!</h2>
<button onClick={() => reset()}>Try again</button>
</body>
</html>
);
}
Now it shows the error on the default error boundary
Middleware is not part of the app router rendering process - there are no react components involved here so no error boundaries are triggered. You have to try/catch and ensure your middleware doesn’t throw
Answer
The error boundary shown above is only present in dev mode, in prod mode likely you will just get an empty 500
CinnamonOP
I see.. Thank you for your help 🙇â€â™‚ï¸