我是 node.js 和 express 的新手。我的 app.js 文件中有以下内容作为最后的错误处理程序:
app.use(function(err, req, res, next){
// we may use properties of the error object
// here and next(err) appropriately, or if
// we possibly recovered from the error, simply next().
res.status(err.status || 500);
console.log(err);
var errMsg = "An internal error occurred. Please notify your system administrator.";
// respond with json
if (req.accepts('json')) {
res.send({error: errMsg});
return;
}
// respond with html page
if (req.accepts('html')) {
res.render('500', errMsg);
return;
}
res.type('txt').send(errMsg);
});
当我终止数据库服务器或以其他方式引发“中间件”级错误时,它在测试期间对我有用,但我不确定当回调收到错误时它是否也会启动?我一直在我的回调中使用这样的东西:
if(err) {
console.log(err);
res.send(500, {error: err});
}
但我想更好地遵守 DRY 原则并找出一种方法来处理全局(跨模块)回调内部的错误,而不是编写一堆相同的代码。如果中间件“catchall”不起作用,我是不是每个模块都有一个全局函数?希望这是有道理的。
最佳答案
看connect-domain中间件。它可以帮助您捕获异步回调、超时等内部的所有错误。仅适用于 node > 0.8.0。
关于Node.js w/在回调中表达错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12348274/