Next.js Discord

Discord Forum

unified error handler

Answered
Mini Rex posted this in #help-forum
Open in Discord
Mini RexOP
Is there any way to catch all errors throw by 'route handler' ? There's no description in the document, so I have to write try catch in every route handler. That's kind of painful
Answered by fuma
I think he is trying to define a default error message for route handlers. The default one is "Internal Server Error", or he has his own function implemented via throw. (For example, catching zod errors and returning a bad request error)

In this case, Next.js doesn't offer a built-in method to implement it. Try creating a wrapper, like:
export const GET = defineRoute(req => {
  throw XXX
})

and you can handle the logic inside of wrapper
View full answer

9 Replies

@Mini Rex Is there any way to catch all errors throw by 'route handler' ? There's no description in the document, so I have to write try catch in every route handler. That's kind of painful
can i ask what is causing the errors, as you may want to fix that... but i don't think you can customize the internal server error to your own liking...
you talking about the api routes in app dir right? (ie /app/test/route.ts)
I think he is trying to define a default error message for route handlers. The default one is "Internal Server Error", or he has his own function implemented via throw. (For example, catching zod errors and returning a bad request error)

In this case, Next.js doesn't offer a built-in method to implement it. Try creating a wrapper, like:
export const GET = defineRoute(req => {
  throw XXX
})

and you can handle the logic inside of wrapper
Answer
ahh yeah that makes sense, and that sound like a good compromise
@riský can i ask what is causing the errors, as you may want to fix that... but i don't think you can customize the internal server error to your own liking...
Mini RexOP
something like permissions. For example, some users do not have permissions to request '/api/a' and '/api/b', I can throw error and handle it in somewhere
your best option if you want to be able to throw anywhere is to use fuma's suggestion and detect error and return accordingly
You may achieve this via middleware if it doesn't require database queries. Otherwise, go with the wrapper solution
ahh yeah i forgot about middlewire as that is done before the actual function is run 🙂