简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM