如果Express处理程序中发生异常,则不会触发Node.js uncaughtException事件

时间:2018-12-01 16:00:53

标签: node.js

发生异常时,我在nodejs应用程序中捕获了uncaughtException事件,以编写日志。

process.on('uncaughtException', (err) => {
    log.warn('Caught exception. Exiting. error: ' + err + ', stack: ' + err.stack);
    process.exit(1);
});

但是,当在Express事件处理程序中引发异常时,不会调用上述处理程序。

someInvalidFunc();    //This causes the uncaughtException handler to get called.

app.all('/ping', function (req, res, next) {
    someInvalidFunc();  //This doesn't cause the uncaughtException handler to get called.
    res.status(200).json({status: 'OK'});
});

即使未调用处理程序,该错误也会打印到控制台。

  

错误:ReferenceError:未定义someInvalidFunc

这是什么原因?如何在应用程序中捕获所有未处理的异常?

1 个答案:

答案 0 :(得分:0)

如果您使用的是Express,我认为可能会发生这种情况,因为它提供了默认错误处理程序,该错误处理程序将捕获控制器中发生的任何错误并默认发送500响应。

您可以覆盖错误处理程序。 在文档中对此进行了解释: https://expressjs.com/en/guide/error-handling.html

相关问题