2

In Swift error handling - how do you know what error type is being thrown without looking at the implementation and how do you handle the case where ErrorType-derived error and NSError can be thrown by the method?

e.g.

Code does not show what type of error will be thrown.

public func decode(jwt: String) throws -> JWT {
    return try DecodedJWT(jwt: jwt)
}
1

1 Answer 1

4

You can catch the thrown error to a variable and do runtime analysis of the variable. E.g., for some unknown implementation:

/* ---------------------- */
/* unknown implementation */
enum HiddenError: ErrorType {
    case SomeError
}

class AnotherError : NSError { }

func foo() throws -> Int {
    let foo = arc4random_uniform(3);
    if foo == 0 {
        throw HiddenError.SomeError
    }
    else if foo == 1 {
        throw AnotherError(domain: "foo", code: 0, userInfo: [:])
    }
    else if foo == 2 {
        throw NSError(domain: "foo", code: 0, userInfo: [:])
    }
    else {
        return Int(foo)
    }
}
/* ---------------------- */

Investigate the error as:

/* "External" investigation */
func bar() throws -> Int {
    return try foo()
}

func fuzz() {
    do {
        let buzz = try bar()
        print("Success: got \(buzz)")
    } catch let unknownError {
        print("Error: \(unknownError)")
        print("Error type: \(unknownError.dynamicType)")
        if let dispStyle = Mirror(reflecting: unknownError).displayStyle {
          print("Error type displaystyle: \(dispStyle)")
        }
    }
}

fuzz()
/* Output examples:

   Error: SomeError
   Error type: HiddenError
   Error type displaystyle: Enum

   //

   Error: Error Domain=foo Code=0 "(null)"
   Error type: AnotherError
   Error type displaystyle: Class

   //

   Error: Error Domain=foo Code=0 "(null)"
   Error type: NSError
   Error type displaystyle: Class             */
Sign up to request clarification or add additional context in comments.

2 Comments

So there is no way to know what error type will be thrown ahead of time?
If the throwing method you're calling is a black box (and no docs), you're left with runtime introspection to investigate what kind of errors the method possibly throws. Generally, however, this shouldn't be the case, and you can knit your catch clauses to the specific errors you expext to be thrown. Note also that all the errors above all conform to ErrorType (and that an error thrown in Swift must be a type conforming to this).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.