在 React Native 应用程序(iOS 和 Android)中作为全局处理程序报告不同的错误是否有解决方案?
我对以下案例感兴趣:
通过报告,我的意思是将它们发送到一些第三方服务,您可以在其中跟踪错误。
最佳答案
在 RN 中有一个 ErrorUtils 全局处理程序,用于处理 RN JS 层的未捕获和捕获的异常。您可以使用它来设置处理程序,例如:
if (ErrorUtils._globalHandler) {
instance.defaultHandler = ErrorUtils.getGlobalHandler && ErrorUtils.getGlobalHandler() || ErrorUtils._globalHandler;
ErrorUtils.setGlobalHandler(instance.wrapGlobalHandler); //feed errors directly to our wrapGlobalHandler function
}
和处理程序方法
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);
}
请注意,在上面的代码中,您需要仅为 android 创建一个节点模块,并在您的 ReactContextBaseJavaModule 中编写一个 React Native 桥接方法:
@ReactMethod
public void reload() {
Activity activity = getCurrentActivityInstance();
Intent intent = activity.getIntent();
activity.finish();
activity.startActivity(intent);
}
谢谢!
关于error-handling - 如何在 React Native 应用程序中报告不同的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42225995/