How to catch a Swift crash and do some logging How to catch a Swift crash and do some logging ios ios

How to catch a Swift crash and do some logging


NSSetUncaughtExceptionHandler works only with NSExceptions. See this SO answer for brilliant explanation.

To catch Swift run time errors implement signal handler for SIGTRAP. As far as I know, Swift code will terminate the program with SIGTRAP exception type if it detects an unexpected condition at runtime i.e only SIGTRAP is helpful to catch Swift errors, rest like SIGSEGV, SIGBUS, SIGILL do not work.I found this info in this apple link.

If your code is a mix both Objective-C and Swift, then implement both NSSetUncaughtExceptionHandler and signal handler to handle crashes.

For understanding and implementing Signal handling refer this link.

Hope this helps.


Swift 5 you can handle app crash like this

NSSetUncaughtExceptionHandler { (exception) in   let stack = exception.callStackReturnAddresses   print("Stack trace: \(stack)")    }


NSSetUncaughtExceptionHandler(&HandleException);signal(SIGABRT, SignalHandler);signal(SIGILL, SignalHandler);signal(SIGSEGV, SignalHandler);signal(SIGFPE, SignalHandler);signal(SIGBUS, SignalHandler);signal(SIGPIPE, SignalHandler);

This will works for most situations. But I'm also trying to find some way to catch all crashes. Well, if you comd+click to those signals to see documents, you will find there are more than 20 kinds of signals, what I've done is signal(,) all most all kinds of signals. That seems works, but maybe still some crash cannot collect.