【问题标题】:Global unhandled rejection handler全局未处理拒绝处理程序
【发布时间】:2018-09-13 06:34:31
【问题描述】:

我使用https://github.com/rtsao/browser-unhandled-rejection 处理全局未处理的拒绝。

这是处理程序的注册方式:

window.addEventListener('unhandledrejection', (params) => {

});

我不确定我应该如何处理这个callback 中的承诺?一切正常,每次promise 失败并且catch 未实现时都会调用此处理程序,所以我得到'Uncaught (in promise)'

有没有办法在unhandledrejection 中处理失败的promise,这样它就不会抛出'Uncaught (in promise)' 错误,并且promise 失败的代码会像catch 一样正常继续?在params 参数中,我可以访问被拒绝的promise,但我不确定我应该如何处理它,或者甚至可能吗?

【问题讨论】:

  • 不,unhandledrejection 事件不是处理错误的地方。它的唯一目的是监视。要正确处理拒绝,请修复您使用 Promise 的代码,即实现 catch 或其他。在正常工作的程序中绝不应该发生未经处理的拒绝。

标签: javascript promise event-handling


【解决方案1】:

根据规范,事件是可以取消的,所以可以添加

params.preventDefault(); // Note: `params` here is more idiomatically called `event`

到您的处理程序以防止默认操作。 (这可以防止 Chrome 上出现“未处理的拒绝”警告,它在没有那个 polyfill 的情况下实现了这一点。)

示例没有 preventDefault:

window.addEventListener("unhandledrejection", event => {
    console.log("Got the unhandledrejection event");
});
Promise.reject();
Look in the real browser console.

示例 preventDefault:

window.addEventListener("unhandledrejection", event => {
    console.log("Got the unhandledrejection event");
    event.preventDefault();
});
Promise.reject();
Look in the real browser console.

【讨论】:

    猜你喜欢
    • 2020-01-06
    • 1970-01-01
    • 2016-01-29
    • 2019-03-15
    • 2016-07-21
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2015-04-24
    相关资源
    最近更新 更多