How to use middleware to catch errors thrown by API?
Unanswered
Gharial posted this in #help-forum
GharialOP
I'm using Next as my backend service, and my existing middleware has implemented the function of api key interception detection. But every api file in my backend code contains a try catch module, which I think is a bit redundant. Is there a way for my middleware to successfully catch these thrown errors and return a corresponding error response to the requester? (I'm using the native fetch api)
3 Replies
GharialOP
Here's my current middleware code:
export function middleware(request: Request) {
const apiKey = request.headers.get("AETHER_API_KEY");
if (apiKey !== env.AETHER_API_KEY) {
return new Response(JSON.stringify({ error: "Invalid API key" }), {
status: 401,
});
}
}European sprat
You'll need to return something in the route handlers when there's an error or whatever else
I ended up making a specific API error handler that is used in the catch of each route handler so it catches any errors, passes it to my errorHandler function and then based on the error it returns an http response code for it. If i don't have a specific entry for a particular error then it returns a default 500 response