javascript - 在 Obj C 中捕获 React Native 错误

标签 javascript ios objective-c exception-handling react-native

我希望防止我的 React Native 应用程序中任何意外引发的异常导致整个应用程序崩溃。

有什么方法可以处理在 obj c 端的 React Native JS 中引发的异常。 由于该过程超出了 App Delegate,简单的 @try/@catch 根本无法解决问题。

我已经实现了 NSSetUncaughtExceptionHandler,我已将其设置为提供故障堆栈跟踪,但在优雅地处理 RN 问题方面还不够

最佳答案

我不得不进行大量研究,因为它的文档非常少。最后,我的一个 friend 帮我解决了这个问题。

你需要设置

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

此外,创建一个 RCTExceptionsManager 实例并将其传递到您的类的 extraModulesForBridge 方法中,遵守 RCTBridgeDelegate 协议(protocol)。

- (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;

这使您可以完全控制致命异常处理,并且 React native 崩溃不会使应用程序崩溃。

关于javascript - 在 Obj C 中捕获 React Native 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35582141/

相关文章:

ios - WKWebView - 无法加载页面并使用 loadHTMLString 设置自定义字体/css

iphone - 匹配一个或多个字母数字的 NSRegularExpression

ios - 如何在两次按钮点击之间设置计时器

javascript - 压缩 webpack 插件

javascript - 如何在 nextjs 上设置粒子背景?

objective-c - Swift NSAttributeType

ios - 尝试从后台恢复时触发 AVAudioSessionInterruptionNotification 和 AVAudioSessionInterruptionWasSuspendedKey

objective-c - cellForItemAtIndexPath 未调用

javascript - Typescript 找不到在 "paths"设置中定义的模块

c# - 将 Canvas 转换为图像并保存到光盘