iOS中程序异常Crash友好化处理详解

Willow ·
更新时间:2024-09-21
· 836 次阅读

前言

前两天接到个面试,面试官问到上线的app怎么避免闪退,首先想到的就是在编码的时候进行各种容错,但貌似并不是面试官想要的答案,所以表现的很糟糕。今天有时间就来整理一下,希望有所帮助。

实现效果如图:


效果实现:


用法:

1.将截图的中CatchedHelper文件夹拖到你的项目工程中。

2.在AppDelegate.m中找到以下方法并如下添加代码:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // Override point for customization after application launch. [UncaughtExceptionHandler installUncaughtExceptionHandler:YES showAlert:YES]; return YES; }

以上代码就可以实现稍微友好一点的crash拦截处理。

代码解释:

UncaughtExceptionHandler.h主要代码:

#import <Foundation/Foundation.h> #import <UIKit/UIKit.h> @interface UncaughtExceptionHandler : NSObject /*! * 异常的处理方法 * * @param install 是否开启捕获异常 * @param showAlert 是否在发生异常时弹出alertView */ + (void)installUncaughtExceptionHandler:(BOOL)install showAlert:(BOOL)showAlert; @end

UncaughtExceptionHandler.m文件主要的代码如下:

1.发送异常信号

/* * 异常的处理方法 * * @param install 是否开启捕获异常 * @param showAlert 是否在发生异常时弹出alertView */ + (void)installUncaughtExceptionHandler:(BOOL)install showAlert:(BOOL)showAlert { if (install && showAlert) { [[self alloc] alertView:showAlert]; } NSSetUncaughtExceptionHandler(install ? HandleException : NULL); signal(SIGABRT, install ? SignalHandler : SIG_DFL); signal(SIGILL, install ? SignalHandler : SIG_DFL); signal(SIGSEGV, install ? SignalHandler : SIG_DFL); signal(SIGFPE, install ? SignalHandler : SIG_DFL); signal(SIGBUS, install ? SignalHandler : SIG_DFL); signal(SIGPIPE, install ? SignalHandler : SIG_DFL); }

产生上述的signal的时候就会调用我们定义的SignalHandler来处理异常。

ps: NSSetUncaughtExceptionHandler就是iOS SDK中提供的一个现成的函数,用来捕获异常的方法,使用方便。但它不能捕获抛出的signal,所以定义了SignalHandler方法。

2.处理异常

void HandleException(NSException *exception) { int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount); // 如果太多不用处理 if (exceptionCount > UncaughtExceptionMaximum) { return; } //获取调用堆栈 NSArray *callStack = [exception callStackSymbols]; NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithDictionary:[exception userInfo]]; [userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey]; //在主线程中,执行制定的方法, withObject是执行方法传入的参数 [[[UncaughtExceptionHandler alloc] init] performSelectorOnMainThread:@selector(handleException:) withObject: [NSException exceptionWithName:[exception name] reason:[exception reason] userInfo:userInfo] waitUntilDone:YES]; }

该方法就是对应NSSetUncaughtExceptionHandler的处理,只要方法关联到这个函数,那么发生相应错误时会自动调用该函数,调用时会传入exception参数。获取异常后会将捕获的异常传入最终调用处理的handleException函数。

3.无法捕获的signal处理

//处理signal报错 void SignalHandler(int signal) { int32_t exceptionCount = OSAtomicIncrement32(&UncaughtExceptionCount); // 如果太多不用处理 if (exceptionCount > UncaughtExceptionMaximum) { return; } NSString* description = nil; switch (signal) { case SIGABRT: description = [NSString stringWithFormat:@"Signal SIGABRT was raised!\n"]; break; case SIGILL: description = [NSString stringWithFormat:@"Signal SIGILL was raised!\n"]; break; case SIGSEGV: description = [NSString stringWithFormat:@"Signal SIGSEGV was raised!\n"]; break; case SIGFPE: description = [NSString stringWithFormat:@"Signal SIGFPE was raised!\n"]; break; case SIGBUS: description = [NSString stringWithFormat:@"Signal SIGBUS was raised!\n"]; break; case SIGPIPE: description = [NSString stringWithFormat:@"Signal SIGPIPE was raised!\n"]; break; default: description = [NSString stringWithFormat:@"Signal %d was raised!",signal]; } NSMutableDictionary *userInfo = [NSMutableDictionary dictionary]; NSArray *callStack = [UncaughtExceptionHandler backtrace]; [userInfo setObject:callStack forKey:UncaughtExceptionHandlerAddressesKey]; [userInfo setObject:[NSNumber numberWithInt:signal] forKey:UncaughtExceptionHandlerSignalKey]; //在主线程中,执行指定的方法, withObject是执行方法传入的参数 [[[UncaughtExceptionHandler alloc] init] performSelectorOnMainThread:@selector(handleException:) withObject: [NSException exceptionWithName:UncaughtExceptionHandlerSignalExceptionName reason: description userInfo: userInfo] waitUntilDone:YES]; }

以上方法是对于捕获不到的signal信号进行处理,列出常见的异常类型。

4.堆栈调用

//获取调用堆栈 + (NSArray *)backtrace { //指针列表 void* callstack[128]; //backtrace用来获取当前线程的调用堆栈,获取的信息存放在这里的callstack中 //128用来指定当前的buffer中可以保存多少个void*元素 //返回值是实际获取的指针个数 int frames = backtrace(callstack, 128); //backtrace_symbols将从backtrace函数获取的信息转化为一个字符串数组 //返回一个指向字符串数组的指针 //每个字符串包含了一个相对于callstack中对应元素的可打印信息,包括函数名、偏移地址、实际返回地址 char **strs = backtrace_symbols(callstack, frames); int i; NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames]; for (i = 0; i < frames; i++) { [backtrace addObject:[NSString stringWithUTF8String:strs[i]]]; } free(strs); return backtrace; }

backtrace是Linux下用来追踪函数调用堆栈以及定位段错误的函数。

5.使用UIAlerView进行友好化提示

- (void)handleException:(NSException *)exception { [self validateAndSaveCriticalApplicationData:exception]; if (!showAlertView) { return; } #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wdeprecated-declarations" UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"出错啦" message:[NSString stringWithFormat:@"你可以尝试继续操作,但是应用可能无法正常运行.\n"] delegate:self cancelButtonTitle:@"退出" otherButtonTitles:@"继续", nil]; [alert show]; #pragma clang diagnostic pop CFRunLoopRef runLoop = CFRunLoopGetCurrent(); CFArrayRef allModes = CFRunLoopCopyAllModes(runLoop); while (!self.dismissed) { //点击继续 for (NSString *mode in (__bridge NSArray *)allModes) { //快速切换Mode CFRunLoopRunInMode((CFStringRef)mode, 0.001, false); } } //点击退出 CFRelease(allModes); NSSetUncaughtExceptionHandler(NULL); signal(SIGABRT, SIG_DFL); signal(SIGILL, SIG_DFL); signal(SIGSEGV, SIG_DFL); signal(SIGFPE, SIG_DFL); signal(SIGBUS, SIG_DFL); signal(SIGPIPE, SIG_DFL); if ([[exception name] isEqual:UncaughtExceptionHandlerSignalExceptionName]) { kill(getpid(), [[[exception userInfo] objectForKey:UncaughtExceptionHandlerSignalKey] intValue]); } else { [exception raise]; } }

在这里你可以做自己的crash收集操作,例如上传服务器等。

源码下载

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对软件开发网的支持。

您可能感兴趣的文章:查看iOS Crash logs的方法iOS10适配之权限Crash问题的完美解决方案iOS Crash常规跟踪方法及Bugly集成运用详细介绍iOS开发之WKWebViewJavascriptBridge Xcode9中导致crash的解决iOS App连续闪退时上报crash日志的方法详解查看iOS已上架App的Crash信息定位、应对处理方式的实例iOS Crash文件分析方法汇总iOS开发笔记之键盘、静态库、动画和Crash定位iOS监控笔记之启动crash



crash 程序 IOS

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章