捕獲系統異常崩潰的方法

一、使用PLCrashReporter框架html

PLCrashReporterConfig *config = [[PLCrashReporterConfig alloc] initWithSignalHandlerType:PLCrashReporterSignalHandlerTypeMach symbolicationStrategy:PLCrashReporterSymbolicationStrategyAll];
    
    PLCrashReporter *reporter = [[PLCrashReporter alloc] initWithConfiguration:config];
    NSData *data = [reporter generateLiveReport];

    PLCrashReport *report = [[PLCrashReport alloc] initWithData:data error:nil];
    
    NSString *reportStr = [PLCrashReportTextFormatter stringValueForCrashReport:report withTextFormat:PLCrashReportTextFormatiOS];
 
    NSLog(@"%@", reportStr);

 二、使用系統NSSetUncaughtExceptionHandler方法ios

若是同時有多方經過NSSetUncaughtExceptionHandler註冊異常處理程序,和平的做法是:後註冊者經過NSGetUncaughtExceptionHandler將先前別人註冊的handler取出並備份,在本身handler處理完後自覺把別人的handler註冊回去,規規矩矩的傳遞。不傳遞強行覆蓋的後果是,在其以前註冊過的日誌收集服務寫出的Crash日誌就會由於取不到NSException而丟失Last Exception Backtrace等信息。(P.S. iOS系統自帶的Crash Reporter不受影響)數組

NSUncaughtExceptionHandler *handler;
-(void)viewDidLoad
{
    //取出以前的NSUncaughtExceptionHandler
    handler = NSGetUncaughtExceptionHandler();
    
    //捕獲exception
    NSSetUncaughtExceptionHandler(uncaughtExceptionHandler);    
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //數組越界,產生崩潰
    NSArray *arr = @[@"aaa", @"bbb"];
    NSLog(@"%@", arr[3]);
}

void uncaughtExceptionHandler(NSException *exception)
{
    //獲取崩潰信息,
    NSLog(@"%@, %@, %@", exception.name, exception.reason, exception.userInfo);
    NSSetUncaughtExceptionHandler(handler);
}

輸出:
NSRangeException, *** -[__NSArrayI objectAtIndex:]: index 3 beyond bounds [0 .. 1], (null)

 

參考文章:框架

http://www.cocoachina.com/ios/20150701/12301.html日誌

http://www.jianshu.com/p/930d7f77df6ccode

相關文章
相關標籤/搜索