我希望防止我的React Native应用程序中的任何意外引发的异常崩溃整个应用程序。
有没有办法在obj c端处理React Native JS中引发的异常。由于该过程超出了App Delegate,简单的@try/@catch
根本不会削减它。
我已经实现了NSSetUncaughtExceptionHandler
,我已经设置了它来提供故障堆栈跟踪,但在优雅处理RN问题方面却不尽如人意
我不得不研究很多,因为它的记录非常糟糕。最后,我的一个朋友帮我解决了这个问题。
你需要设置
//This will tell react native that you are taking responsibility of fatal crashes.
RCTSetFatalHandler(^(NSError *error) {});
此外,创建一个RCTExceptionsManager实例并将其传递给您的类的extraModulesForBridge方法,遵循RCTBridgeDelegate协议。
- (NSArray *)extraModulesForBridge:(RCTBridge *)bridge {
return @[[RCTExceptionsManager alloc] initWithDelegate:self];
}
您需要实现的两种方法是:
- (void)handleSoftJSExceptionWithMessage:(NSString *)message stack:(NSArray *)stack exceptionId:(NSNumber *)exceptionId;
- (void)handleFatalJSExceptionWithMessage:(NSString *)message stack:(NSArray *)stack exceptionId:(NSNumber *)exceptionId;
这使您可以完全控制致命的异常处理,并使本机崩溃不会使应用程序崩溃。