Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
498 views
in Technique[技术] by (71.8m points)

swift2 - Swift error handling - determining the error type

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)
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...