產(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