0

Is there a solution for reporting different errors in React Native application (iOS and Android) as a global handler?

I am interested in following cases:

  1. Unhandled rejections
  2. Unhandled exceptions
  3. Errors on the native side

By reporting, I mean sending them to some third-party service where you can track errors.

2

1 Answer 1

3

In RN there is a ErrorUtils global handler, that handle uncaught and caught exceptions for your RN JS layer. You can use this to set a handler like:

if (ErrorUtils._globalHandler) {
            instance.defaultHandler = ErrorUtils.getGlobalHandler && ErrorUtils.getGlobalHandler() || ErrorUtils._globalHandler;
            ErrorUtils.setGlobalHandler(instance.wrapGlobalHandler);  //feed errors directly to our wrapGlobalHandler function
        }

And handler method

async wrapGlobalHandler(error, isFatal){

      const stack = parseErrorStack(error);

     //Add this error locally or send it your remote server here

      //*> Finish activity
      setTimeout (() => {
        instance.defaultHandler(error, isFatal);  //after you're finished, call the defaultHandler so that react-native also gets the error
        if (Platform.OS == 'android') {
          NodeModule.reload()
        }
      }, 1000);
  }

Notice in above code you need to create a node module for android only and write a React Native bridge method there in your ReactContextBaseJavaModule:

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

Thanks!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot! Can you please update your response to use ErrorUtils.setGlobalHeader. It appears that it is now the way to go.
You can use it in any JS component of your top hierarchy of JS components

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.