The express.js website confused me, because there are two contradictory statements:
You define error-handling middleware last, after other app.use() and routes calls
– /guide/error-handling.html
and
All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response
– /starter/faq.html
It seems to be telling me that both of these middleware layers should be the last ones in the stack...? Erm, so what, I am meant to add two app.use
middleware layers last? That is not possible...
Anyway, obviously one of these pages forgot to mention the exception of the other, so I'd like to know: which middleware should I register last? My error-handler or my 404-handler?
app.use(function(req, res, next) {
res.status(404).send('Sorry cant find that!');
});
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
Also I'm wondering, do I need to call next
from within either handler?
The order doesn't really matter as your last middleware only gets called, when in some middleware before next(err)
has been called. Your 404 middleware will always get called if nothing else has handled (and finished) the request.
And for your second question: no, you don't want to call next()
in either of those as you finish the request with res.send()
.
Edit: I would leave the order like that though as the 404 middleware is not really an error handler.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.