【发布时间】:2016-07-10 11:05:45
【问题描述】:
我正在使用从教程书中获取的这段代码。我用护照实现了用户,app.use 检查UnauthorizedError 是教程推荐的检查对应用程序受限部分的未授权访问的方法。
每当我输入错误的网址时,网站就会挂起,没有错误处理,也没有消息发送到浏览器。我昨天花了很大一部分时间检查我的路线,似乎没有明显的问题。
然后,今天我凭着一个小小的预感将Unauthorized error 的错误检查注释掉了,瞧,错误处理又好了。关于这里发生的事情以及如何正确实施此错误检查的任何建议?
注意:当存在对已知 URL 良好路由的实际未经授权访问时,此错误检查确实有效。但是,即使已登录,它仍然不会捕获错误的 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;
【问题讨论】: