首页 > 解决方案 > Nodejs进程无异常崩溃

问题描述

当我的 nodejs 应用程序中发生未捕获的异常时,我将日志条目写入日志。

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

但是,今天有几次,该应用程序在没有写入日志条目的情况下崩溃了。

两次应用程序在处理类似请求时都崩溃了,所以这主要是由于应用程序的一些问题,而不是因为有人杀死了它或其他一些外部因素。

那么,有什么方法可以让应用程序崩溃而不给出未捕获的异常?

标签: javascriptnode.jspromisees6-promise

解决方案


我也会建议你添加unhandledRejection。正如Node.js文档所提到的,

unhandledRejection每当一个 Promise 被拒绝并且在事件循环的一个轮次中没有错误处理程序附加到该 Promise 时,就会发出该事件。使用 Promises 进行编程时,异常被封装为“被拒绝的 Promise”。可以使用 Promise 链捕获和处理拒绝,promise.catch()并通过 Promise 链进行传播。该unhandledRejection事件对于检测和跟踪被拒绝但尚未处理的承诺很有用。

下面是Node.js再次提供的如何使用它的示例:

process.on('unhandledRejection', (reason, p) => {
  console.log('Unhandled Rejection at:', p, 'reason:', reason);
  // application specific logging, throwing an error, or other logic here
});

somePromise.then((res) => {
  return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)
}); // no `.catch()` or `.then()`

推荐阅读