React Native中的全局未处理注释侦听器

时间:2018-01-28 13:53:34

标签: javascript react-native error-handling promise

是否有

的等价物

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

在React Native?

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

2 个答案:

答案 0 :(得分:4)

这不是一个容易的问题。

"未处理的拒绝"所有浏览器尚不支持该事件(请参阅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
  }
};

答案 1 :(得分:0)

您不必安装另一个 promise 实现,只需使用 RN 附带的实现即可。

global.Promise = require('promise')

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