【问题标题】:Global unhandledrejection listener in React NativeReact Native 中的全局 unhandledrejection 监听器
【发布时间】:2018-07-07 07:29:22
【问题描述】:

有没有等价的

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

在 React Native 中?

我知道我可以包装 fetch api 以在一个地方处理大多数 unhandledrejection 事件,但全局处理程序将帮助处理任何承诺,而不仅仅是来自 fetch api 的承诺。

【问题讨论】:

    标签: javascript react-native error-handling promise


    【解决方案1】:

    这不是一个简单的问题。

    并非所有浏览器都支持“unhandledrejection”事件(请参阅browser compatibility on MDN)。并且默认的 React Native 的 Promises 实现有另一种机制来捕获未处理的拒绝(参见here)。

    如果您仍然想要该功能(我自己也想要!),您可以使用实现它的 JS Promise 库。 Bluebird 就是一个很好的例子。但是你必须确保你的应用程序中的每个 Promise 都使用这个实现。

    例如,在您的 React Native 应用程序的 index.js 文件中:

    import Promise from 'bluebird';
    
    // We use the "Bluebird" lib for Promises, because it shows good perf
    // and it implements the "unhandledrejection" event:
    global.Promise = Promise;
    
    // Global catch of unhandled Promise rejections:
    global.onunhandledrejection = function onunhandledrejection(error) {  
      // Warning: when running in "remote debug" mode (JS environment is Chrome browser),
      // this handler is called a second time by Bluebird with a custom "dom-event".
      // We need to filter this case out:
      if (error instanceof Error) {
        logError(error);  // Your custom error logging/reporting code
      }
    };
    

    【讨论】:

    • > 但是你必须确保你的应用程序中的每个 Promise 都使用这个实现。嗨 Pierre,您能详细说明如何确保应用程序中的每个 Promise 都应该使用它吗?这是否意味着将import Promise from 'bluebird';global.Promise = Promise; 放在每个 Javascript 文件中?
    • 嗨@ashishb,如果您修改global 对象(此处为global.Promise)上的属性,这意味着它可以在运行时从您应用程序的所有JS 代码(每个文件)中使用。这就是为什么这里我们在 index.js 文件中初始化这个属性,它是应用程序代码的入口点。
    【解决方案2】:

    你不必安装另一个promise实现,你可以简单地使用RN自带的。

    global.Promise = require('promise')
    
    require('promise/lib/rejection-tracking').enable({
      allRejections: true,
      onUnhandled: (id, error) => {
        ...
      }
    })
    

    【讨论】:

    猜你喜欢
    • 2022-01-17
    • 2011-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-15
    • 1970-01-01
    • 2022-12-01
    相关资源
    最近更新 更多