快速路由 - 未经授权的错误处理程序挂起错误路由



我正在使用从教程书中获取的这段代码。我用护照实现了用户,app.use检查UnauthorizedError是教程推荐的检查检查未经授权访问应用程序受限部分的方法。

每当我输入一个错误的网址时,网站就会挂起,没有错误处理,也没有消息发送到浏览器。我昨天花了很大一部分时间检查我的路线,似乎没有明显的问题。

然后今天我凭着一点预感注释掉了Unauthorized error的错误检查,瞧,错误处理又很好了。对这里发生的事情以及如何正确实施此错误检查的任何建议?

注意:当实际未经授权访问已知网址良好路由时,此错误检查确实有效。但是,即使登录,它仍然不会捕获错误的URL。

app.use('/', routes);
app.use('/api', routesApi);
// 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 handlers
// Catch unauthorised errors
app.use(function (err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
    res.status(401);
    res.json({"message" : err.name + ": " + err.message});
  }
});
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

也许,您必须调用 next() 将错误转发到下一个错误处理程序。

app.use(function (err, req, res, next) {
  if (err.name === 'UnauthorizedError') {
    res.status(401);
    res.json({"message" : err.name + ": " + err.message});
  } else
    next(err);
});

最新更新