Register for swift_willThrow inside swift programs

When tracking down bugs it's sometimes helpful to get a backtrace of the call to throw together with the error description itself.

If errors bubble up to some global catch block, it doesn't seem to be possible to access the backtrace of the throw that triggered the error anymore (or is it?).

In the debugger it's possible to set a symbolic breakpoint for swift_willThrow. My idea is that I somehow register for this hook in a release build and save backtraces in Thread.current.threadDictionary. Then, if the error wasn't catched before the global catch, the backtrace would be written to the logs.

Is it possible to register a handler for swift_willThrow from within a swift program?

swift_willThrow is for debugging purposes only. There's no guarantee of whether or how many times it may be called, so there's no mechanism for installing in-process instrumentation for it.

Ok, thank you. So is there another way to get the backtrace of an error at the time it was thrown? If not, is this something that is considered to be added to Swift in the future?

You could capture the site of the error by adding #file and #line arguments to your errors' initializers, perhaps.

1 Like

Yes, although that only works for custom errors and not from errors from Foundation or other frameworks.