這是一個很小的例子,它可能在閉包中拋出一個錯誤。
首先設置錯誤枚舉:
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 {
}
我們不能處理錯誤,而內部的塊? –
你可以使用rethrows –