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

ded*_*lux 2 routes node.js express

我正在使用从教程书中获取的代码。我使用护照实现了用户,并且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;
Run Code Online (Sandbox Code Playgroud)

Aik*_*wai 5

也许,您必须调用 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);
});
Run Code Online (Sandbox Code Playgroud)