How Next.js 13 middleware is used as error handling?
My Next is currently used as a back-end framework, and the middleware only processes related api files. Now I have implemented the function of uniformly detecting apiKey, but I also want to add an error capture function for all apis. How to achieve it?
4 Replies
Here is my existing code
But this doesn't work, I can't catch related errors thrown by my api, for example my POST api:
I don't want to add a try catch module to each of my api codes. Doing so would defeat my original intention of using middleware to catch errors. So do you guys have any good insights?
Middleware works perfectly to check apiKeys because it runs before your api function. It wouldn't work well to catch errors because it only runs once before your api function. Where I think you have gone wrong is you think you run the api from the middleware file, like calling a function. Unfortunately that's not correct from what I see in the docs, the function prepares another http request which is sent to the api function.
On the other hand middleware on vercel is run on a completely different instance to where your api function is run.
I may be wrong, I am new to this stuff as well😀
Correct, the middleware has no way of knowing if the api has an error. Middleware acts as a door, once the request is past the door it can’t see anything else