react-native: [JS] JS API for global handling of unhandled exceptions

The API I envision is similar to window.onerror but not necessarily the same. This would allow us to make RCTExceptionsManager.reportUnhandledException a lot smaller (we’d move much of the code into JS to keep the current behavior) and make it easier to do custom error handling.

About this issue

  • Original URL
  • State: closed
  • Created 9 years ago
  • Comments: 31 (24 by maintainers)

Commits related to this issue

Most upvoted comments

Exactly @qbig

Basically

if (!__DEV__) {
  ErrorUtils.setGlobalHandler(error => {
    sentry.capture(error);
    NativeModules.BridgeReloader.reload()
  });
}

Then your BridgeReloader would be an objC module that simply calls [_bridge reload]

Or in an Android module, you just get the running activity, finish it, and restart it

@ReactMethod
public void reload() {
  Activity activity = getCurrentActivity();
  Intent intent = activity.getIntent();
  activity.finish();
  activity.startActivity(intent);
}

Here: https://github.com/facebook/react-native/blob/d33b554f5d4bb7856cf2fc21175bab23d8225fe4/packager/react-packager/src/Resolver/polyfills/error-guard.js

var ErrorUtils = {
  _inGuard: 0,
  _globalHandler: null,
  setGlobalHandler: function(fun) {
    ErrorUtils._globalHandler = fun;
  },
//...

‘setGlobalHandler’ would overwrite a lot of the RN behaviour (eg. RedBox in development). Understanding that we could just monkey patch globalHandler, the "" seems alarming. So maybe an API like addGlobalHandler, so that we could add custom handler without breaking the default behaviour and and without messing with “internal” variables ? @ide @satya164

That’s neat:) @ajwhite Thanks so much! I guess you are not using the raven-js plugin? which does something like :

    ErrorUtils.setGlobalHandler(Raven.captureException.bind(Raven));

But I don’t like the fact that it is overwriting the default exception handler.

So I was considering something like

    var defaultHandler = ErrorUtils._globalHandler;
    ErrorUtils._globalHandler = function(...args){
      defaultHandler(...args);
      Raven.captureException(...args);
      // other custom handler
    };

This would be great for adding something like Bugsnag to report exceptions when apps are in production.

Edit: In fact, I think ErrorUtils.setGlobalHandler((err, isFatal) => { ... }); might do the job here.