iOS 捕獲異常

產(chǎn)品測試和上線后往往會遇到一些bug,開發(fā)者需要定位到異常的代碼這個時候就要捕獲異常。

可以通過寫一個類CrashExceptioinCatcher,在類中定義一個靜態(tài)方法startCrashExceptionCatch, 方法里調(diào)NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);

綁定void uncaughtExceptionHandler(NSException *exception)方法處理異常信息,在void uncaughtExceptionHandler(NSException *exception)里將異常打印出來,并附帶上設(shè)備信息提交至服務(wù)器,這樣在測試時候能夠比較有效的收集異常信息。

頭文件
#import <Foundation/Foundation.h>
#import <objc/runtime.h>

@interface CatchCrash : NSObject

void uncaughtExceptionHandler(NSException *exception);

@end
實現(xiàn)文件
void uncaughtExceptionHandler(NSException *exception)
{
    // 異常的堆棧信息
    NSArray *stackArray = [exception callStackSymbols];
    // 出現(xiàn)異常的原因
    NSString *reason = [exception reason];
    // 異常名稱
    NSString *name = [exception name];
    NSString *exceptionInfo = [NSString stringWithFormat:@"Exception reason:%@\nException name:%@\nException stack:%@",name, reason, stackArray];
    // 異常出處
    NSString * mainCallStackSymbolMsg = [CatchCrash getMainCallStackSymbolMessageWithCallStackSymbols:stackArray];
    
    NSMutableArray *tmpArr = [NSMutableArray arrayWithArray:stackArray];
    [tmpArr insertObject:reason atIndex:0];
    NSString * errorPlace = [NSString stringWithFormat:@"Error Place%@",mainCallStackSymbolMsg];
        NSLog(@"初始化完畢%@",errorPlace);
    
    NSString * file =[NSString stringWithFormat:@"%@/Documents/error.log",NSHomeDirectory()] ;
    //保存到本地  --  當(dāng)然你可以在下次啟動的時候,上傳這個log
    [exceptionInfo writeToFile:file atomically:YES encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"打印出來看看____%@",exceptionInfo);
}
使用方法
    //注冊消息處理函數(shù)的處理方法
    NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);
    
    ViewController *testVc = [[ViewController alloc] init];
    self.window.rootViewController = testVc;
    
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
DEMO地址

https://github.com/godwar10/CatchCrash

寫在最后
大神勿噴,最近才寫記錄下方便以后查找。希望能和大家一起學(xué)習(xí)交流進(jìn)步。如果覺得好請賞點小錢——謝謝。 祝大家代碼永無bug

最后編輯于
?著作權(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)容

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