【问题标题】:Getting UnhandledPromiseRejectionWarning even when catching exceptions即使在捕获异常时也得到 UnhandledPromiseRejectionWarning
【发布时间】:2022-06-16 06:01:46
【问题描述】:

在 NodeJS 中,我有一些这样的代码:

function doSomethingAsync() {
    return Promise.reject("error");
}

function main() {
    doSomethingAsync().catch();
}

当我运行这段代码时,我得到一个UnhandledPromiseRejectionWarning

我知道将调用函数 asyncawaiting doSomethingAsync 放在 try/catch 内会使错误消失,但在这种情况下,我不想添加使函数异步并等待只是消除错误的额外复杂性,所以我更喜欢使用catch()

为什么我的错误处理方法不能消除错误?

【问题讨论】:

    标签: node.js promise unhandled-promise-rejection


    【解决方案1】:

    .catch() 实际上并没有捕捉到任何东西。

    如果我们查看docs

    在调用它的对象上内部调用Promise.prototype.then,传递参数undefined 和接收到的onRejected 处理程序。

    找到规范 here

    如果我们再查看docs 中的Promise.then,我们会发现:

    onRejected:如果Promise 被拒绝,则调用Function。这个函数有一个参数,rejection reason如果它不是函数,则在内部将其替换为“Thrower”函数(它会抛出作为参数接收的错误)。

    因此,.catch() 实际上不会捕获任何内容,您的应用程序将继续抛出错误。您必须将函数传递给catch()

    这样做会使错误静音:

    doSomethingAsync().catch(() => { });
    

    更新说这实际上是在页面顶部调用here,但我只是错过了。

    【讨论】:

      猜你喜欢
      • 2022-11-30
      • 1970-01-01
      • 2017-05-05
      • 2013-08-12
      • 2021-03-11
      • 2022-06-15
      • 2023-03-13
      • 1970-01-01
      • 2014-11-09
      相关资源
      最近更新 更多