2016-04-17 113 views
4

我的功能:如何在關閉時拋出錯誤?

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


} 

但我需要這樣的東西異常結束塊內投擲

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


} 

,這樣我可以在裏面塊本身處理錯誤。

回答

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

如果你想使用這個重新拋出異常的代碼示例從這個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 { 
} 
+0

我們不能處理錯誤,而內部的塊? –

+2

你可以使用rethrows –