Error handling 如何在闭包中抛出错误?

Error handling 如何在闭包中抛出错误?,error-handling,swift2.2,Error Handling,Swift2.2,我的职能: func post(params: AnyObject, completion: (response : AnyObject ) -> Void) { } 但我需要像在完成块中抛出错误这样的东西 func post(params: AnyObject, completion: (response : **throws ->** AnyObject ) -> Void) { } 因此,我可以处理块本身内部的错误这是一个小示例,说明如何在闭包中抛出错误 首次

我的职能:

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


}
但我需要像在完成块中抛出错误这样的东西

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


}

因此,我可以处理块本身内部的错误

这是一个小示例,说明如何在闭包中抛出错误

首次设置错误枚举:

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,此代码示例取自:

enum NumberError:ErrorType{
案例超过32max
}
func functionWithCallback(callback:(Int)throws->Int)rethrows{
尝试回调(Int(Int32.max)+1)
}
做{

尝试函数withcallback({v in,如果可以使用rethrows)
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 {
}