如何在关闭时抛出错误?

时间:2016-04-17 09:09:02

标签: error-handling swift2.2

我的功能:

func post(params: AnyObject, completion: (response : AnyObject ) -> Void) {


}

但我需要在完成块内输入错误

func post(params: AnyObject, completion: (response : **throws ->** AnyObject ) -> Void) {


}

这样我就可以处理阻止内部的错误

1 个答案:

答案 0 :(得分:2)

这是一个很小的例子,它可以在关闭时抛出错误。

首先设置错误枚举:

enum TestError : ErrorType {
    case EmptyName
    case EmptyEmail
}

比你的功能应该抛出错误:

func loginUserWithUsername(username: String?, email: String?) throws -> String {
    guard let username = username where username.characters.count != 0 else {
        throw TestError.EmptyName
    }

    guard let email = email where email.characters.count != 0 else {
        throw TestError.EmptyEmail
    }

    return username
}

比创建块来调用它:

func asynchronousWork(completion: (inner: () throws -> TestError) -> Void) -> Void {
    do {
        try loginUserWithUsername("test", email: "")
    } catch let error {
        completion(inner: {throw error})
    }
}

处理类似的错误:

asynchronousWork { (inner: () throws -> TestError) -> Void in
    do {
        let result = try inner()
    } catch TestError.EmptyName {
        print("empty name")
    } catch TestError.EmptyEmail {
        print("empty email")
    } catch {
        print(error)
    }
}

如果您想要使用rethrows,此代码示例取自link

enum NumberError:ErrorType {
    case ExceededInt32Max
}

func functionWithCallback(callback:(Int) throws -> Int) rethrows {
    try callback(Int(Int32.max)+1)
}

do {
    try functionWithCallback({v in if v <= Int(Int32.max) { return v }; throw NumberError.ExceededInt32Max})
}
catch NumberError.ExceededInt32Max {
    "Error: exceeds Int32 maximum"
}
catch {
}