如何设置Node.js错误处理?

时间:2017-04-03 05:07:25

标签: javascript node.js error-handling

我有节点7.8.0,我已阅读Node.js Best Practice Exception Handling

我似乎无法理解node.js中的错误处理。

我的http

server.on('error', () => console.log('Here I should be replacing
the Error console.'));

对于404我有这段代码

app.use((req, res, next) => {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});
app.use((err, req, res) => {
  res.status(err.status);
  res.render('error');
});

正在捕获404,它会创建Error对象,然后通过正确呈现错误视图来处理它。但它也会向我的控制台抛出错误日志,我不知道它来自何处以及如何阻止它。

我想使用自己的错误处理,并且实际上从未将404等错误写入控制台。

我尝试过的代码似乎不起作用。

var server = http.createServer(app);
const onError = () => console.log('Here I should be replacing the Error console.');
server.on('error', onError);
server.on('uncaughtException', onError);
process.on('uncaughtException', onError);

2 个答案:

答案 0 :(得分:0)

这是由于expressjs。 Expressjs如果env不等于测试,则所有错误都会写入控制台。

function logerror(err) {
  if (this.get('env') !== 'test') console.error(err.stack || err.toString());
}

http.Server也没有名为错误的事件。

答案 1 :(得分:0)

我不确定它是如何呈现错误视图的,因为错误处理程序需要4个参数而你只传递它3.这就是Express可以区分错误处理程序和普通路由处理程序的方法(记录在案) here)。

请改为尝试:

app.use((err, req, res, next) => {
  res.status(err.status);
  res.render('error');
});