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

node.js Node.js

ALEYHarry

2020-03-24

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

(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块的方法?

第3341篇《如何在Node.js UnhandledPromiseRejectionWarning中查找未处理的承诺?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
老丝LEY 2020.03.24

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

节点--trace-warnings app.js

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

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

That module supports Bluebird, ES6 Promises, Q, WhenJS, es6-promise, then/promise, and anything that conforms to any of the unhandled rejection specifications (full details in the documentation).

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android