路由器内的Express错误处理程序不起作用

时间:2017-08-01 07:32:30

标签: node.js express

我有一个像这样的全球https://github.com/cexbrayat/angular-cli-diff/compare/1.4.0...1.5.0的快速申请:

app.use(function (err, req, res, next) {
  console.error(err.stack)
  res.status(500).send('Something broke!')
})

现在,我已经重构了应用程序,只为错误处理和相关视图设置了专用error handling middleware(应用程序向用户显示了错误消息,隐藏了内部错误):

var express = require('express');
var app = express();

// add one or more routers that throw errors
var myRouter = express.Router();
router.get('/', function(req, res, next) {
     next(new Error('Internal error'));
});
// more handlers...

// ...and finally the new errors router
var errRouter = express.Router();
errRouter.use(function(err, req, res, next) {
  logError(err);
  renderNiceErrorView(err);
});

app.use(errRouter);

但是现在这个错误处理程序在路由器内部,它不再捕获错误。

1 个答案:

答案 0 :(得分:3)

问题在于路由错误时表达router,而路由器函数looks for a four parameter function(req,res,next)就像标准中间件一样。

因此,应该在应用程序上直接声明一个catch-all错误处理程序:

app.use(function (err, req, res, next) {
    // TODO: handle the error
});

这是has only threeexpected行为:您可以在这些链接中找到更多信息和其他方法来构建代码。仔细阅读它们。

如果您想了解快速路由的工作原理,请启动应用程序并启用debug并检查标志:

DEBUG=express:* node --inspect index.js

然后打开Chrome devtools,将它们附加到您的进程,在引发错误的行上添加断点(或手动抛出错误)并使用step-into,step-over按钮 play