Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
449 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...