React Native中的全局未处理拒绝侦听器

Mar*_*gno 4 javascript error-handling promise react-native

有什么等效的

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

在React Native中?

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

pie*_*d_2 6

这不是一个容易的问题。

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

如果仍然想要该功能(我自己也想要它!),可以使用实现它的JS Promise库。蓝鸟就是一个很好的例子。但是随后您必须确保应用中的每个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
  }
};
Run Code Online (Sandbox Code Playgroud)