更好的異常捕獲方式

使用 NSSetUncaughtExceptionHandler 方法,將異常信息寫入日志文件。

首先新加一個類 DSQCrashCatch ,.h中定義方法:

+ (void)catchCrash;

在 didFinishLaunchingWithOptions 中設(shè)置該方法:

[DSQCrashCatch?catchCrash]




@implementation DSQCrashCatch

void uncaughtExceptionHandler(NSException * exception);

+ (void)catchCrash {

? ? staticdispatch_once_tonceToken;

? ? dispatch_once(&onceToken, ^{

? ? ? ? NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);

? ? });

}

void uncaughtExceptionHandler(NSException * exception){

? ? //獲取系統(tǒng)當前時間,(注:用[NSDate date]直接獲取的是格林尼治時間,有時差)

? ? NSDateFormatter *formatter =[[NSDateFormatter alloc] init];

? ? [formattersetDateFormat:@"yyyy-MM-dd HH:mm:ss"];

? ? NSString*crashTime = [formatterstringFromDate:[NSDatedate]];

? ? [formattersetDateFormat:@"HH-mm-ss"];

? ? NSString*crashTimeStr = [formatterstringFromDate:[NSDatedate]];

? ? [formattersetDateFormat:@"yyyyMMdd"];

? ? NSString*crashDate = [formatterstringFromDate:[NSDatedate]];

? ? //異常的堆棧信息

? ? NSArray*stackArray = [exceptioncallStackSymbols];

? ? //出現(xiàn)異常的原因

? ? NSString*reason = [exceptionreason];

? ? //異常名稱

? ? NSString*name = [exceptionname];

? ? //拼接錯誤信息

? ? NSString *exceptionInfo = [NSString stringWithFormat:@"CrashTime: %@\nException reason: %@\nException name: %@\nException call stack:%@\n", crashTime, name, reason, stackArray];

? ? //把錯誤信息保存到本地文件,設(shè)置errorLogPath路徑下

? ? //并且經(jīng)試驗,此方法寫入本地文件有效。

//? ? NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;

? ? NSString*errorLogPath = [NSStringstringWithFormat:@"%@/CrashLogs/%@/",NSHomeDirectory(), crashDate];

? ? NSFileManager *manager = [NSFileManager defaultManager];

? ? if(![managerfileExistsAtPath:errorLogPath]) {

? ? ? ? [managercreateDirectoryAtPath:errorLogPath withIntermediateDirectories:true attributes:nil error:nil];

? ? }

? ? errorLogPath = [errorLogPathstringByAppendingFormat:@"%@.log",crashTimeStr];

? ? NSError*error =nil;

? ? NSLog(@"%@", errorLogPath);

? ? BOOLisSuccess = [exceptionInfowriteToFile:errorLogPathatomically:YESencoding:NSUTF8StringEncodingerror:&error];

? ? if(!isSuccess) {

? ? ? ? NSLog(@"將crash信息保存到本地失敗: %@", error.userInfo);

? ? }

}

@end

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 簡介: 利用NSSetUncaughtExceptionHandler可以用來處理異常崩潰。崩潰報告系統(tǒng)會用NSS...
    飛哥漂流記閱讀 6,396評論 0 8
  • 為了更好的維護iOSApp,處理程序崩潰是必需要做的,那么如何收集用戶使用時出現(xiàn)的崩潰呢? 1.應(yīng)用崩潰收集方法:...
    白如晝閱讀 2,552評論 0 1
  • 1. 精簡代碼 優(yōu)點:代碼在代碼塊中只在代碼塊中有效,減少對其他作用域命名污染。 缺點:可讀性差。 NSURL *...
    追著公車的少年_4934閱讀 271評論 0 0
  • 1.不可變數(shù)組轉(zhuǎn)變?yōu)榭勺償?shù)組聲明實例變量的數(shù)組 必須記得實現(xiàn) 對于遍歷數(shù)組找到對象后 如果還需要查找 記得先結(jié)束 ...
    小新xin閱讀 1,044評論 0 1
  • 夜鶯2517閱讀 128,214評論 1 9

友情鏈接更多精彩內(nèi)容