异常捕获

异常捕获 有两种

  • IOS系统的异常
    • NSSetUncaughtExceptionHandler(&exceptionHandler);// exceptionHandler是捕获的回调函数
  • C或者C++ 里面的异常 // signalHandler 也是回调函数
    • signal(SIGHUP, signalHandler);
    • signal(SIGINT, signalHandler);
    • signal(SIGQUIT, signalHandler);
    • signal(SIGABRT, signalHandler);
    • signal(SIGILL, signalHandler);
    • signal(SIGSEGV, signalHandler);
    • signal(SIGFPE, signalHandler);
    • signal(SIGBUS, signalHandler);
    • signal(SIGPIPE, signalHandler);
void signalHandler(int signal) {
    
    volatile int32_t _uncaughtExceptionCount = 0;
    int32_t exceptionCount = OSAtomicIncrement32(&_uncaughtExceptionCount);
    
    // 如果太多不用处理
    if (exceptionCount > _uncaughtExceptionMaximum) {
        return;
    }
    // 获取信息
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:[NSNumber numberWithInt:signal] forKey:SignalExceptionKey];
    NSArray *stackArray = [JHCatchCrash backtrace];
    userInfo[StackAddressesExceptionKey] = stackArray;
    NSLog(@"signalHandler: %@", userInfo);
    // 现在就可以保存信息到本地[]
   
}

void exceptionHandler(NSException *exception) {
    
    volatile int32_t _uncaughtExceptionCount = 0;
    int32_t exceptionCount = OSAtomicIncrement32(&_uncaughtExceptionCount);
    
    // 如果太多不用处理
    if (exceptionCount > _uncaughtExceptionMaximum) {
        return;
    }
    // 异常的堆栈信息
    NSArray *stackArray = [exception callStackSymbols];
    /* 异常理由和名字**/
    NSString *exceptionInfo = [NSString stringWithFormat:@"Exception reason:%@;Exception name:%@",[exception reason], [exception name]];
    NSMutableDictionary *userInfo =[NSMutableDictionary dictionary];
    userInfo[UncaughtExceptionKey] = exceptionInfo;
    userInfo[StackAddressesExceptionKey] = stackArray;
    NSLog(@"exceptionHandler: %@", userInfo);
    // 现在就可以保存信息到本地[]

}


//获取调用堆栈
+ (NSArray *)backtrace {
    
    void* callstack[128];
    int frames = backtrace(callstack, 128);
    char **strs = backtrace_symbols(callstack,frames);
    
    NSMutableArray *backtrace = [NSMutableArray arrayWithCapacity:frames];
    for (int i=0;i

你可能感兴趣的:(异常捕获)