How can I properly end a middleware chain in case of error ?
In my code I have
if (someProblem) {
res.status(statuscode).json({message: 'oops'});
return;
}
Yet the midleware in the chain after that keeps getting called giving me the Can't set headers after they are sent
error.
We can use more than one middleware on an Express app instance, which means that we can use more than one middleware inside app.
The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Middleware functions are functions that have access to the request object (req), the response object (res), and the next middleware function in the application's request-response cycle. These functions are used to modify req and res objects for tasks like parsing request bodies, adding response headers, etc.
Middleware does not advance on its own. It only goes to the next step in the chain when you call next()
so as long as you don't call next()
, then the next step will not execute.
So, if you just send a response and return (without calling next()
), then you should not have an issue.
The code you show in your question would not, all by itself, cause the error message you refer to so there must be more going on that you aren't showing us for that error to occur.
So you simply have to attach an errorHandler (which is a function that takes 4 parameters) before you create the actual server instance.
Anywhere in the app you can now simply create an error with var newError = new Error('my error message');
and pass it to the next
callback with next(newError);
To stop the execution after the error has been thrown and to not send a response twice use return next (newError);
// example route
app.get('/test', function(req, res, next){
if (someProblem) {
var newError = new Error('oops');
return next(newError);
}
res.send('all OK - no errors');
});
// attach this errorHandler just before you create the server
app.use(function(error, req, res, next){
console.log(error);
res.status(500).json(error);
});
// this is where you create the server
var server = app.listen(4000, function(){
console.log('server started');
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With