4

我的 Express 应用程序中的一个常见模式是在我的所有路线中包含以下内容:

//...code which could result in an err
if (!err) return res.send(200);
console.log(err); // Would prefer to omit this line
res.send(500);

现在,我需要写下console.log(err)我所有的路线。我宁愿在err每次发送 500 时自动记录变量。有没有办法连接到 Express 并自动记录调用堆栈和/或err所有 500 个响应?

4

1 回答 1

7

根据您的解释,您似乎在所有路线中都包含错误处理。您可能应该创建一个全局拦截器错误处理程序,它可以为您执行日志记录,并且如果您有 500 错误类型,它仍然是基本错误处理程序。

//if your express var is app

var errorHandler = function(err, req, res, next){
   console.log(err.stack);
   res.send(500);
   // or you could call res.render('error'); if you have a view for that.
};

app.use(app.router); // this has to come before your interceptors
app.use(notFound);  // your page not found interceptor
app.use(errorHandler);
于 2013-01-14T05:16:00.877 回答