Swift error handling - determining the error type

2019-01-29 05:10发布

问题:

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:

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             */