如何在React Native应用程序中报告不同的错误?

时间:2017-02-14 12:18:18

标签: error-handling exception-handling react-native crash-reports

是否存在将React Native应用程序(iOS和Android)中的不同错误报告为全局处理程序的解决方案?

我对以下案件感兴趣:

  1. 未处理的拒绝
  2. 未处理的例外
  3. 原生方面的错误
  4. 通过报告,我的意思是将它们发送到可以跟踪错误的第三方服务。

1 个答案:

答案 0 :(得分:2)

在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);
    }

谢谢!