本文档简要介绍了如何使用 iOS 版 Google Analytics(分析)SDK v2 进行崩溃和异常衡量。
概览
崩溃和异常衡量功能可帮助您衡量您的应用中发生的崩溃和异常的次数及类型。Google Analytics(分析)中的异常包括:
-
NSString
(可选)说明 - 对异常情况的说明(最多 100 个字符)。接受nil
。 boolean
isFatal - 指示异常是否严重。YES
表示严重。
崩溃和异常数据主要在“崩溃和异常”报告中提供。
捕获的异常
捕获的异常是指您的应用中已为其定义异常处理代码的错误。这些通常是您预计会在正常使用应用期间发生的错误,而您希望应用能够从这些错误中恢复,例如在请求数据期间偶尔出现网络连接超时。
您可以将 sendException:
添加到异常处理代码的 catch
代码块中来衡量捕获的异常。
在以下示例中,应用尝试从云端加载最高得分列表。如果请求超时(可能是由于网络连接缓慢),我们会先向 Google Analytics(分析)发送异常,然后再为用户处理该异常:
@try { NSArray *highScores = [self getHighScores]; } @catch (NSException *exception) { [tracker sendException:NO // Boolean indicates non-fatal exception. withDescription:@"Connection timout %d: %@", connectionError, errorDescription]; }
您可以使用 sendException:withDescription:withNSException:
自动填充异常的说明字段,其中包含名称和原因,如以下示例所示:
@try { NSArray *highScores = [self getHighScores]; } @catch (NSException *exception) { [tracker sendException:NO withNSException:exception); }
如需使用错误网域、代码和说明自动填充错误,请使用 sendException:withDescription:withNSError:
,如下所示:
NSError *error = nil; if (![self updateHighScoresWithError:&error]) { [tracker sendException:NO withNSError:error); }
衡量未捕获的异常
未捕获的异常表示应用在运行时遇到意外情况的实例,这些异常通常是严重的,会导致应用因此崩溃。您可以将 sendUncaughtExceptions
属性设置为 YES
,从而自动向 Google Analytics(分析)发送未捕获的异常。这可以通过应用委托的 application:didFinishLaunchingWithOptions
方法方便地完成:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [GAI sharedInstance].sendUncaughtExceptions = YES; // Enable // ... the rest of your code, include other GAI properties you want to set. }
使用自动异常衡量功能时,请注意以下事项:
- 所有使用自动异常衡量功能发送的异常都会在 Google Analytics(分析)中显示为严重异常。
- 说明字段使用堆栈轨迹自动填充。