如何在Node.js UnhandledPromiseRejectionWarning中找到未处理的承诺?

问题描述 投票:140回答:3

来自版本7的Node.js具有async / await语法糖用于处理promise,现在在我的代码中经常会出现以下警告:

(node:11057) UnhandledPromiseRejectionWarning: Unhandled promise 
rejection (rejection id: 1): ReferenceError: Error: Can't set headers 
after they are sent.
(node:11057) DeprecationWarning: Unhandled promise rejections are 
deprecated. In the future, promise rejections that are not handled 
will terminate the Node.js process with a non-zero exit code.

不幸的是,没有提到缺少捕获的线。有没有办法找到它而不检查每个try / catch块?

node.js promise async-await warnings unhandled-exception
3个回答
259
投票

unhandledRejection进程的事件。

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

64
投票

显示未处理的ES6 Promise拒绝的完整堆栈跟踪的正确方法是使用--trace-warnings标志运行Node.js。这将显示每个警告的完整堆栈跟踪,而不必从您自己的代码中拦截拒绝。例如:

node --trace-warnings app.js

确保trace-warnings标志位于.js文件的名称之前!否则,该标志将被解释为您的脚本的参数,Node.js本身将忽略该标志。

如果你想实际处理未处理的拒绝(例如通过记录它们),那么你可能想要使用我的unhandled-rejection模块,它使用单个事件处理程序捕获支持它的每个主要Promises实现的所有未处理的拒绝。

该模块支持Bluebird,ES6 Promises,Q,WhenJS,es6-promisethen/promise以及任何符合任何未处理拒绝规范的内容(文档中的完整详细信息)。


2
投票

使用堆栈跟踪记录

如果您正在寻找更多有用的错误消息。尝试将此添加到您的节点文件。它应该显示崩溃发生的完整堆栈跟踪。

process.on('unhandledRejection', (error, p) => {
  console.log('=== UNHANDLED REJECTION ===');
  console.dir(error.stack);
});
© www.soinside.com 2019 - 2024. All rights reserved.