2016-04-17 26 views
4

Meine Funktion:Wie wird ein Fehler beim Schließen ausgelöst?

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


} 

aber ich brauche so etwas wie Fehler innerhalb Abschluss Block

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


} 

so dass ich Griff Fehler innerhalb Block selbst werfen.

Antwort

2

Es ist kleines Beispiel, wie es möglich ist, einen Fehler in Schließung zu werfen.

Erste aufgebaut Fehler Enum:

enum TestError : ErrorType { 
    case EmptyName 
    case EmptyEmail 
} 

als youre Funktion Fehler werfen sollten:

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 
} 

als Block schaffen es für den Aufruf:

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

Handle Fehler wie es:

Falls möchten Sie rethrows diesem Codebeispiel verwenden, wurde aus diesem link genommen:

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

können wir nicht Fehler ohne innere Blöcke behandeln? –

+2

können Sie rethrows dafür verwenden –

Verwandte Themen