如何在本机中捕获未捕获的异常(全局)

时间:2015-06-18 14:35:06

标签: react-native

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

5 个答案:

答案 0 :(得分:25)

您可能会覆盖React Native用于开发的异常日志记录:

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

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

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

答案 1 :(得分:13)

我就是这样做的:

第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
}

多数民众赞成!

答案 2 :(得分:5)

您可以尝试https://github.com/master-atul/react-native-exception-handler

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

答案 3 :(得分:4)

有一种本土方式。

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

只需将您的报告逻辑放在customDelegate

答案 4 :(得分:2)

现在有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中间件。

相关问题