Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

javascript - Global unhandledrejection listener in React Native

Is there any equivalent for

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

in React Native?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is not an easy issue.

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).

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...