Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching React Native error in Obj C

I am looking to prevent any unexpected raised Exceptions in my React Native app from crashing the entire app.

Is there any way to handle exceptions raised in the React Native JS on the obj c side. Since the process extends beyond the App Delegate, a simple @try/@catch simply doesn't cut it.

I already have implemented NSSetUncaughtExceptionHandler which I have set up to provide a failure stack trace, but it falls short in terms of gracefully handling RN Issues

like image 646
DanHabib Avatar asked Jul 08 '26 23:07

DanHabib


1 Answers

I had to research a lot because it's very poorly documented. In the end, a friend of mine helped me out with this problem.

You need to set

//This will tell react native that you are taking responsibility of fatal crashes.
RCTSetFatalHandler(^(NSError *error) {}); 

Also, create an RCTExceptionsManager instance and pass it in the extraModulesForBridge method of your class abiding by RCTBridgeDelegate protocol.

- (NSArray *)extraModulesForBridge:(RCTBridge *)bridge {
    return @[[RCTExceptionsManager alloc] initWithDelegate:self];
}

The two methods that you need to implement are:

 - (void)handleSoftJSExceptionWithMessage:(NSString *)message stack:(NSArray *)stack exceptionId:(NSNumber *)exceptionId;
 - (void)handleFatalJSExceptionWithMessage:(NSString *)message stack:(NSArray *)stack exceptionId:(NSNumber *)exceptionId;

This gives you full control of the fatal exception handling and react native crashes won't crash the app.

like image 138
jarora Avatar answered Jul 11 '26 11:07

jarora



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!