快速错误处理 - 确定错误类型 [英] Swift error handling - determining the error type

查看:138
本文介绍了快速错误处理 - 确定错误类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Swift错误处理中 - 您如何知道在不查看实现的情况下抛出什么错误类型,并且如何处理方法可以抛出ErrorType派生错误和NSError的情况?

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?

例如

代码不显示将会抛出什么类型的错误。

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

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


推荐答案

您可以将引发的错误捕获到变量中,并对变量进行运行时分析。例如,一些未知的实现:

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

调查错误为:

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

这篇关于快速错误处理 - 确定错误类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆