Get line causing error in catch?

Is this for debugging during development or at runtime (e.g. to print to some log)?

For the former, you should be able to break on swift_willThrow in lldb.

For the latter, you use a wrapper error type and a helper function to wrap errors thrown from the functions you call:

struct SourceLocationError<T: Error>: Error {
    let file: String, line: Int, error: T
}

func annotateError<T>(_ proc: @autoclosure () throws -> T, file: String = #file, line: Int = #line) throws -> T {
    do {
        return try proc()
    } catch {
        throw SourceLocationError(file: file, line: line, error: error)
    }
}

And then use it like this:

do {
    try annotateError(someFunction())
} catch {
    print(error)
}

Sadly, from what I tried, pre-/postfix operators cant have extra arguments, even when they have default values. That would have made it a bit less visually obtrusive, but if that is an issue a shorter wrapper function name should go a long way.

1 Like