为什么下面的handler被识别为404 handler

Why is the following handler identified as 404 handler

我正在查看express生成器生成的app.js,有如下代码:

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);
});

我的问题是为什么最后一个中间件函数被识别为应该返回not found错误时执行的函数?

是否基于以下假设:如果调用此函数,则意味着没有其他 middleware/router 函数使用 res.send() 完成处理请求,因此对该请求不感兴趣,所以可能请求没有处理程序?如果是这样,那么这个 404 处理函数应该总是最后添加,对吗?

正如你所说的,正如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!")
})