Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I capture / log a fatal error in Swift?

Tags:

swift

For example, fatal error: unexpectedly found nil while unwrapping an Optional value. Regardless of the cause, can this data be captured? Is this stderr or something else?

Edit: I found a reference at http://swiftdoc.org/func/fatalError/ that says the function (which I'm assuming is indeed what Swift is internally calling) "Unconditionally print a message and stop execution.". So perhaps there's nothing left to do but get ahold of the remote crash report via TestFlight crash reports or actually having the device handy.

I'm able to log all uncaught exceptions via NSSetUncaughtExceptionHandler in main.swift, and we have good logging going on in other parts of our app wherever bad (but possible) errors can occur. I was hoping to also log these fatal errors so that our logs show a more complete picture of crashes occuring on remote testing devices.

like image 554
Charlie Schliesser Avatar asked Nov 10 '22 13:11

Charlie Schliesser


1 Answers

Certain errors will go to stderr. Here is a simple example:

$ cat tryit 
#! /usr/bin/env swift

println ("foo")
precondition (false, "bar")
$ ./tryit 2> /tmp/error 1> /tmp/noterror
Illegal instruction: 4
$ cat /tmp/noterror 
$ cat /tmp/error
precondition failed: bar: file ./tryit, line 4
0  swift                    0x000000010f7faa18 llvm::sys::PrintStackTrace(__sFILE*) + 40
1  swift                    0x000000010f7faef4 SignalHandler(int) + 452
...

If you remove the precondition, then the results go to stdout:

$ cat tryit 
#! /usr/bin/env swift

println ("foo")
$ ./tryit 2> /tmp/error 1> /tmp/noterror
$ cat /tmp/noterror 
foo
$ cat /tmp/error 
like image 58
GoZoner Avatar answered Dec 29 '22 02:12

GoZoner