In Objective-C, the NSSetUncaughtExceptionHandler
can register some functionality to do some last minute logging about the exception.
This doesn't catch something crashing from Swift.
Is it possible to do something like this at a global level in Swift? E.g. do some logging if a crash happens in Swift code, like forced unwrapping a nil optional.
Specifically, I'm doing a utility to log network traffic in the app, and I would like to flush my in-memory data to disk if a crash happens.
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 withSIGTRAP
exception type if it detects an unexpected condition at runtime i.e onlySIGTRAP
is helpful to catch Swift errors, rest likeSIGSEGV
,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.
There are multiple aspects to your questions, let me try to answer them:
NSSetUncaughtExceptionHandler
only catches uncaught exceptions which is only a small subset of possible crashes.To your specific scenario: you should not do that and not try to. This may cause user data to get corrupted or more data to be lost. The app crashed hard with serious issues, rather fix the issue.
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.