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 */
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…