javascript - Nodejs进程无异常崩溃
问题描述
当我的 nodejs 应用程序中发生未捕获的异常时,我将日志条目写入日志。
process.on('uncaughtException', function (err) {
log.warn('Caught exception. Exiting. error: ' + err + ", stack: " + err.stack);
process.exit(1);
});
但是,今天有几次,该应用程序在没有写入日志条目的情况下崩溃了。
两次应用程序在处理类似请求时都崩溃了,所以这主要是由于应用程序的一些问题,而不是因为有人杀死了它或其他一些外部因素。
那么,有什么方法可以让应用程序崩溃而不给出未捕获的异常?
解决方案
我也会建议你添加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()`
推荐阅读
- django - 使用列表中的字段名称创建 django 模型
- sql-server - MS SQL Server - Datediff 不包括周末
- reactjs - NextJs、Redux、Redux Saga 通用化简器示例
- wpf - 使用 Dictionary 作为子函数或函数中的参数
- html - css根据最大长度内容设置表格td边框
- c# - Task.Delay 与 Thread.Sleep 的区别
- html - 如何使 codemirror 响应
- html - 我怎样才能删除这个锚:悬停标签问题
- emacs - 投影仪导出中的 Tikz 字体
- java - 将代码从 HashMap 转换为 ArrayList