更好的异常捕获方式

使用 NSSetUncaughtExceptionHandler 方法,将异常信息写入日志文件。

首先新加一个类 DSQCrashCatch ,.h中定义方法:

+ (void)catchCrash;

在 didFinishLaunchingWithOptions 中设置该方法:

[DSQCrashCatch catchCrash]




@implementation DSQCrashCatch

void uncaughtExceptionHandler(NSException * exception);

+ (void)catchCrash {

    staticdispatch_once_tonceToken;

    dispatch_once(&onceToken, ^{

        NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);

    });

}

void uncaughtExceptionHandler(NSException * exception){

    //获取系统当前时间,(注:用[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];

    //出现异常的原因

    NSString*reason = [exceptionreason];

    //异常名称

    NSString*name = [exceptionname];

    //拼接错误信息

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

    //把错误信息保存到本地文件,设置errorLogPath路径下

    //并且经试验,此方法写入本地文件有效。

//    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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容