如何在 React Native 中捕获未捕获的异常(全局)



>有谁知道捕获所有未捕获的异常(全局)的最佳方法是什么,以便我可以将崩溃报告发送回服务器?我似乎无法在反应原生文档或 github 上找到任何信息。

你可以覆盖 React Native 用于开发的异常日志记录:

ErrorUtils.setGlobalHandler(function() {
// your handler here
});

https://github.com/facebook/react-native/blob/522fd33d6f3c8fb339b0dde35b05df34c1233306/Libraries/JavaScriptAppEngine/Initialization/InitializeJavaScriptAppEngine.js#L46

然后,您可能需要编写一些 Obj-C 并公开给 JS,具体取决于您的确切要求。

这就是我的做法:

第 1 步:我们拦截反应原生错误处理程序,如下所示:

//intercept react-native error handling
if (ErrorUtils._globalHandler) {
  this.defaultHandler = ErrorUtils.getGlobalHandler && ErrorUtils.getGlobalHandler() || ErrorUtils._globalHandler;
  ErrorUtils.setGlobalHandler(this.wrapGlobalHandler);  //feed errors directly to our wrapGlobalHandler function
}

步骤2:现在,每当出现未处理的错误时,都会调用我们的wrapGlobalHandler。因此,对此函数中的错误执行任何您想要的操作。

然后对错误执行一些操作:

async function wrapGlobalHandler(error, isFatal){
    const stack = parseErrorStack(error);
    //do anything with the error here
    this.defaultHandler(error, isFatal);  //after you're finished, call the defaultHandler so that react-native also gets the error
}

完整代码在这里:

import stacktraceParser from 'stacktrace-parser';

const parseErrorStack = (error) => {
    if (!error || !error.stack) {
        return [];
    }
    return Array.isArray(error.stack) ? error.stack :
    stacktraceParser.parse(error.stack);
};

// intercept react-native error handling
if (ErrorUtils._globalHandler) {
    this.defaultHandler = (ErrorUtils.getGlobalHandler
        && ErrorUtils.getGlobalHandler())
        || ErrorUtils._globalHandler;
    ErrorUtils.setGlobalHandler(this.wrapGlobalHandler); // feed errors directly to our wrapGlobalHandler function
}
async function wrapGlobalHandler(error, isFatal) {
    const stack = parseErrorStack(error);
    //do anything with the error here
    this.defaultHandler(error, isFatal);  //after you're finished, call the defaultHandler so that react-native also gets the error
}

就是这样!

你可以

试试 https://github.com/master-atul/react-native-exception-handler。

一个 react 本机模块,允许您注册全局错误处理程序,该处理程序可以捕获致命/非致命未捕获的异常。该模块有助于防止 RN 应用突然崩溃,而不会向用户发送正常消息。

有一种原生的方式。

RCTBridge *bridge = [[RCTBridge alloc] initWithBundleURL:_scriptURL
                                      moduleProvider:^{
                                        id<RCTExceptionsManagerDelegate> customDelegate = ...
                                        return @[[RCTExceptionsManager initWithDelegate:customDelegate];
                                      }
                                       launchOptions:nil];

只需将您的报告逻辑放在customDelegate中即可。

现在有 react-native-error-reporter,它以一种非常简单的方式完成了这个技巧:

npm i react-native-error-reporter --save
rnpm link

然后将以下行添加到代码中:

import ErrorReporter from 'react-native-error-reporter';
ErrorReporter.init("vanson@vanportdev.com", "My App's Crash Report");

如果你使用的是 Redux,你可能想尝试 redux-catch 中间件。

最新更新