Express中间件错误处理程序

Zan*_*nko 4 node.js express

按照生成的快递模板.在app.js下面有一个代码片段

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

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
Run Code Online (Sandbox Code Playgroud)

根据我的理解,中间件将按顺序从app.use('/users', users)404处理程序运行到错误处理程序.我的问题是如何才能到达错误处理程序并执行此行res.status(err.status || 500);?不是每个失败的请求都首先通过404处理程序,因此获取状态代码404?如果我错过了什么,请告诉我!谢谢

ale*_*mac 9

不,它不会.如果查看这些事件处理程序声明,您将看到未处理错误的错误处理程序,还有一个附加err参数:

app.use(function(req, res, next) {
app.use(function(err, req, res, next) {
Run Code Online (Sandbox Code Playgroud)

错误处理中间件总是需要四个参数.您必须提供四个参数以将其标识为错误处理中间件函数.即使您不需要使用下一个对象,也必须指定它以维护签名.否则,下一个对象将被解释为常规中间件,并且将无法处理错误.有关错误处理中间件的详细信息.

因此,当找不到路由时,最后声明的中间件正在调用,它是404错误处理程序.

但是当你调用next错误时:next(err)或者你的代码抛出错误,最后一个错误处理程序正在调用.