Thursday, August 27, 2015

Capturing Swift Error Context

Erica Sadun:

Say you’re working with a type and you want to throw an error that reflects the context of where it originates. You can do that, mostly, using a few built-in compiler keywords. __FUNCTION__, __LINE__, and __FILE__ provide literal interpolation about the details of a calling function[…]

[…]

Use a protocol to automatically pick up on type context. The default implementation in the following Contextualizable extension refers to self.dynamicType in a way that a method signature cannot.

I’ve long been doing this sort of thing in Objective-C with macros. It’s a bug help when debugging or tracking down what happened on a customer’s Mac. Unlike the macros, this won’t build up a stack trace of how the error was propagated, although you could approximate that using -[NSThread callStackSymbols].

Previously: Swift and Cocoa Error Handling, JSErrorStackTrace, NSXReturnThrowError.

2 Comments RSS · Twitter

[…] to use macros to add tracing information to errors when propagating them. In Swift, I’ve seen this tip for tracking the source of errors that you create, but that isn’t most […]

[…] with C++. However, I think the code is actually very useful because I want to record useful stack traces when throwing or propagating an […]

Leave a Comment