Reputation: 15654
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.
Upvotes: 14
Views: 16166
Reputation: 111
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');
});
Upvotes: 3
Reputation: 688
If you want your middleware to not go to the next step of the chain but to return the error you have to call next(error)
callback.
This will call the error handler middleware where you can operate with the error and return it to the client if thats what you want.
To implement your custom error handler middleware you can use handleError(err, req, res, next)(error, req, res, next)
Upvotes: 2
Reputation: 707158
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.
Upvotes: 27