Asynchronous error handling in swift 2

So, I tried to handle the error in swift 2. But one thing I'm not sure about is how to make it work for asynchronous callback functions. Suppose I load a resource from a backend. I defined my error type as follows:

enum NetworkError: ErrorType { case NoConnection case InvalidJSON case NoSuccessCode(code: Int) } 

I plan on throwing one of these cases when something is wrong. Here is the function that makes the network call:

 func loadRequest<T: Decodable>(request: NSURLRequest, callback:T -> Void) throws { let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(request) { data, response, error in // Other code that parses json and at somewhere it throws throw NetworkError.NoConnection } } 

But here the compiler gives an error:

Cannot call dataTaskWithRequest using argument list of type (NSURLRequest, (_,_,_) throws) -> Void)

Hence it is obvious that the same type of closure is considered as another type when it is declared using throws .

So how does this do-try-catch operation work in these situations?

+6
source share
2 answers

The error cannot be called asynchronously, because the function has already returned when an error occurred, you need to handle the error in closing by contacting some function with the ErrorType parameter to decide what you want to do with it. Example:

 import Foundation enum NetworkError: ErrorType { case NoConnection case InvalidJSON case NoSuccessCode(code: Int) } func getTask() -> NSURLSessionDataTask? { let session = NSURLSession.sharedSession() let urlRequest = NSURLRequest(URL: NSURL(string: "www.google.com")!) return session.dataTaskWithRequest(urlRequest) { data, response, error in if let error = error { asyncError(error) } else { // Do your stuff while calling asyncError when an error occurs } } } func asyncError(error: ErrorType) { switch error { case NetworkError.NoConnection: // Do something break default: break } } 
+3
source

Nothing in NSURLSession.h seems to throw an exception. So I wonder if this class has been converted to use this new functionality.

0
source

Source: https://habr.com/ru/post/989039/


All Articles