zoukankan      html  css  js  c++  java
  • 捕获未处理的Promise错误

    译者按: 通过监听unhandledrejection事件,可以捕获未处理的Promise错误。

    为了保证可读性,本文采用意译而非直译,并且对源代码进行了大量修改。另外,本文版权归原作者所有,翻译仅用于学习。

    使用Promise编写异步代码时,使用reject来处理错误。有时,开发者通常会忽略这一点,导致一些错误没有得到处理。例如:

    function main() {
        asyncFunc()
        .then(···)
        .then(() => console.log('Done!'));
    }

    这篇博客将分别介绍在浏览器与Node.js中,如何捕获那些未处理的Promise错误。由于没有使用catch方法捕获错误,当asyncFunc()函数reject时,抛出的错误则没有被处理。

    浏览器中未处理的Promise错误

    一些浏览器(例如Chrome)能够捕获未处理的Promise错误。

    unhandledrejection

    监听unhandledrejection事件,即可捕获到未处理的Promise错误:

    window.addEventListener('unhandledrejection', event => ···);

    promise: reject的Promise这个事件是PromiseRejectionEvent实例,它有2个最重要的属性:

    • reason: Promise的reject值

    示例代码:

    window.addEventListener('unhandledrejection', event =>
    {
        console.log(event.reason); // 打印"Hello, Fundebug!"
    });
    
    function foo()
    {
        Promise.reject('Hello, Fundebug!');
    }
    
    foo();

    rejectionhandledFundebugJavaScript错误监控插件监听了unhandledrejection事件,因此可以自动捕获未处理Promise错误。

    当一个Promise错误最初未被处理,但是稍后又得到了处理,则会触发rejectionhandled事件:

    window.addEventListener('rejectionhandled', event => ···);

    示例代码:这个事件是PromiseRejectionEvent实例。

    window.addEventListener('unhandledrejection', event =>
    {
        console.log(event.reason); // 打印"Hello, Fundebug!"
    });
    
    window.addEventListener('rejectionhandled', event =>
    {
        console.log('rejection handled'); // 1秒后打印"rejection handled"
    });
    
    
    function foo()
    {
        return Promise.reject('Hello, Fundebug!');
    }
    
    var r = foo();
    
    setTimeout(() =>
    {
        r.catch(e =>{});
    }, 1000);

     

    Node.js中未处理的Promise错误

    监听unhandledRejection事件,即可捕获到未处理的Promise错误:

    process.on('unhandledRejection', (reason, promise) => ···);


    示例代码:

    process.on('unhandledRejection', reason =>
    {
        console.log(reason); // 打印"Hello, Fundebug!"
    });
    
    function foo()
    {
        Promise.reject('Hello, Fundebug!');
    }
    
    foo();

    注: Node.js v6.6.0+ 默认会报告未处理的Promise错误,因此不去监听unhandledrejection事件也没问题。

    FundebugNode.js错误监控插件监听了unhandledRejection事件,因此可以自动捕获未处理Promise错误。

    参考

    关于Fundebug

    Fundebug专注于JavaScript、微信小程序、微信小游戏、支付宝小程序、React Native、Node.js和Java线上应用实时BUG监控。 自从2016年双十一正式上线,Fundebug累计处理了10亿+错误事件,付费客户有Google、360、金山软件、百姓网等众多品牌企业。欢迎大家免费试用

    版权声明

    转载时请注明作者 Fundebug以及本文地址:
    https://blog.fundebug.com/2017/10/09/unhandled-pomise-rejection/
  • 相关阅读:
    儿子和女儿——解释器和编译器的区别与联系
    求eclipse中的java build path 详解
    求eclipse中的java build path 详解
    System.Activator类
    htmlagilitypack解析html
    KindleEditor insertfile初始化多个
    按住ALT键复制
    隐藏行错误排查
    列类型: 202错误
    C#中的&运算
  • 原文地址:https://www.cnblogs.com/fundebug/p/7655106.html
Copyright © 2011-2022 走看看