我是新來的node.js和express。我在app.js文件作爲最後的手段錯誤處理程序如下:Node.js w/express回調中的錯誤處理
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'不起作用,我堅持每個模塊的全局函數嗎?希望這是有道理的。
的確似乎錯誤的中間件不趕回調中的錯誤... – esp