React Native中的全局未处理注释侦听器 [英] Global unhandledrejection listener in React Native

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

问题描述

是否有任何等价物

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

我知道我可以将fetch api包装起来处理大部分在一个地方的未处理的拒绝事件,但全局处理程序将帮助任何承诺不仅来自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中的全局未处理注释侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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