gpt4 book ai didi

error-handling - 如何在关闭时抛出错误?

转载 作者:行者123 更新时间:2023-12-04 08:28:48 24 4
gpt4 key购买 nike

我的功能:

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


}

但我需要像 Error throwing inside completion 块之类的东西
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)
}
}

如果您想使用重新抛出,此代码示例取自 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 {
}

关于error-handling - 如何在关闭时抛出错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36674633/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com