I'm looking through app.js
generated by express generator, and there is the following code:
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
My question is why the last middleware function is identified as a function that is executed when not found
error should be returned?
Is it based on the assumption that if this function is called it means that no other middleware/router function finished processing the request with res.send()
and hence wasn't interested in the request, so probably there is no handler for the request? And if so, than this 404
handler function should always be added last, correct?
It is exactly as you said, as stated in http://expressjs.com/en/starter/faq.html
How do I handle 404 responses? In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. 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:
app.use(function (req, res, next) { res.status(404).send("Sorry can't find that!") })