【发布时间】:2017-10-05 16:24:19
【问题描述】:
Node.js 版本 7 具有用于处理承诺的 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.
不幸的是,没有提到 catch 丢失的行。 有没有办法在不检查每个 try/catch 块的情况下找到它?
【问题讨论】:
-
您可以使用 Bluebird Promise 库,它可能会为您提供堆栈跟踪。
-
也许注册到 Node 的
unhandledRejection事件会有所帮助?请参阅docs。您的回调获得了Error对象和实际的Promise,我相信Error对象可能包含堆栈跟踪。 -
如果前面的两个 cmets 没有帮助,那么
Can't set headers after they are sent.应该会给您一个线索,它可能会在您的代码中发生(即您在标头已经存在之后设置标头的地方)发送 - 大概是因为无法理解异步代码,但这是一个猜测) -
您好,消息有助于确定错误在代码中的位置,顺便说一句,这不像知道行那么容易。
-
@jfriend00 事实证明这是异步函数抛出错误的情况——那些异步函数的内部节点承诺永远不会使用 Bluebird,所以拥有 Bluebird 并没有帮助那个场景。
标签: node.js promise async-await warnings unhandled-exception