异常捕获

2017-03-17  本文已影响48人  LeeDev

异常捕获 有两种

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<frames;i++) {
        [backtrace addObject:[NSString stringWithUTF8String:strs[i]]];
    }
    free(strs);
    return backtrace;
}
上一篇下一篇

猜你喜欢

热点阅读