React Native 中的全局 unhandledrejection 监听器 [英] Global unhandledrejection listener in React Native

查看:51
本文介绍了React Native 中的全局 unhandledrejection 监听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有等价物

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

在 React Native 中?

in React Native?

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

I know I could wrap the fetch api to handle most of the unhandledrejection events in a single place but the global handler would help with any promise not only the one coming from the fetch api.

推荐答案

这不是一个容易的问题.

This is not an easy issue.

并非所有浏览器都支持unhandledrejection"事件(请参阅MDN 上的浏览​​器兼容性).默认的 React Native 的 Promises 实现有另一种机制来捕获未处理的拒绝(请参阅此处).

The "unhandledrejection" event is not yet supported by all browsers (see browser compatibility on MDN). And the default React Native's Promises implementation has another mechanism to catch unhandled rejections (see here).

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

If you want the functionality anyway (I wanted it also myself!), you can use a JS Promise library that implements it. Bluebird is a good example. But then you have to make sure every Promise in your app uses this implementation.

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

For example, in the index.js file of your React Native app:

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
  }
};

这篇关于React Native 中的全局 unhandledrejection 监听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆