【问题标题】:iOS. How I can caught exception, when other code already uses NSSetUncaughtExceptionHandler?IOS。当其他代码已经使用 NSSetUncaughtExceptionHandler 时,我如何捕获异常?
【发布时间】:2016-10-15 03:14:12
【问题描述】:

我想使用全局异常处理程序。

在 applicationdidFinishLaunchingWithOptions 中调用这个:

NSSetUncaughtExceptionHandler(&uncaughtExceptionHandler);

并使用它来处理异常:

    void uncaughtExceptionHandler(NSException *exception) {
        // handling exception
}

但我也使用 sdk,它已经使用了 NSSetUncaughtExceptionHandler。那么当异常发生时我的方法 uncaughtExceptionHandler 没有被调用。

我知道它只能是一个应用程序的一个处理程序。但我需要那个和 sdk,而且这段代码可以处理全局级别的异常。

您对在这种情况下如何使用 NSSetUncaughtExceptionHandler 有任何想法吗?或其他想法如何处理全局级别的异常? 非常感谢。

【问题讨论】:

    标签: ios objective-c xcode exception-handling


    【解决方案1】:

    在 SDK NSSetUncaughtExceptionHandler 覆盖处理程序后调用 installUncaughtExceptionHandler()。比你的uncaughtExceptionHandler 会被调用。

    此外,您还可以存储 SDK 的处理程序,并在您的uncaughtExceptionHandler 中调用它以使 SDK 协同工作。

    示例代码:

    static NSUncaughtExceptionHandler *exceptionHandler = NULL;
    
    typedef void (*sighandler_t)(int);
    static sighandler_t sigHandler = NULL;
    
    static void handleException(NSException *e)
    {
        //your code ...
    
        //call the SDK handler
        if (exceptionHandler) {
            exceptionHandler(e);
        }
    }
    
    static void handleSignal(int signal)
    {
        //your code ...
    
        if (sigHandler) {
            sigHandler(signal);
        }
    }
    
    void installUncaughtExceptionHandler()
    {
        // store the SDK handler
        exceptionHandler = NSGetUncaughtExceptionHandler();
    
        NSSetUncaughtExceptionHandler(&handleException);
    
        sigHandler = signal(SIGABRT, handleSignal);
        signal(SIGILL, handleSignal);
        signal(SIGSEGV, handleSignal);
        signal(SIGFPE, handleSignal);
        signal(SIGBUS, handleSignal);
        signal(SIGPIPE, handleSignal);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-20
      • 2020-10-26
      • 2021-08-06
      • 2011-12-14
      • 2018-12-14
      相关资源
      最近更新 更多