Skip to content

Instantly share code, notes, and snippets.

@acegreen
Last active November 1, 2016 04:34
Show Gist options
  • Save acegreen/4eae768fc1f74cf66cfc to your computer and use it in GitHub Desktop.
Save acegreen/4eae768fc1f74cf66cfc to your computer and use it in GitHub Desktop.
Swift 2.0 Error Handling Asynchronous Functions
**** Medium Story ****
https://medium.com/ios-os-x-development/logan-wright-i-just-started-dabbling-with-swift-s-error-handling-myself-5e7b3dffdf06#.zbor79r8l
public enum Errors: ErrorType {
case NoInternetConnection
case QueryResponseError
case ErrorQueryingForData
case QueryDataEmpty
public func message() -> String {
switch self {
case .NoInternetConnection:
return "No internet connection!\nMake sure your device is connected to begin search"
case .QueryResponseError:
return "Query response invalid!"
case .ErrorQueryingForData:
return "Query Error!"
case .QueryDataEmpty:
return "QueryData Empty!"
}
}
static let allErrors = [NoInternetConnection, QueryResponseError, ErrorQueryingForData, QueryDataEmpty]
}
public func querySomething(queryString: String, completion: (result: () throws -> NSData) -> Void) -> Void {
if let queryUrl: NSURL = NSURL(string: queryString) {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(queryUrl, completionHandler: { (queryData, response, error) -> Void in
guard error == nil else { return completion(result: {throw Errors.ErrorQueryingForData})}
guard queryData != nil else { return completion(result: {throw Errors.QueryDataEmpty})}
return completion(result: { queryData! })
})
task.resume()
}
}
querySomething("http://www.google.ca") { (result) -> Void in
do {
let result = try result()
// 1. Parse results
// 2. Load UI on main queue
dispatch_async(dispatch_get_main_queue(), { () -> Void in
})
} catch {
// handle error
if let error = error as? Errors {
switch error {
case .ErrorQueryingForData:
print(error.message())
case .QueryDataEmpty:
print(error.message())
default:
break
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment