completion swift error handling code example

Example 1: swift get error from the from completion

let task = session.dataTask(with: urlRequest) {
  (data, response, error) in
  // check for any errors
  guard error == nil else {
    print("error calling GET on /todos/1")
    print(error!)
    return
  }
  // make sure we got data
  guard let responseData = data else {
    print("Error: did not receive data")
    return
  }
  // parse the result as JSON, since that's what the API provides
  do {
    guard let todo = try JSONSerialization.jsonObject(with: responseData, options: [])
      as? [String: Any] else {
      print("error trying to convert data to JSON")
      return
    }
    // now we have the todo
    // let's just print it to prove we can access it
    print("The todo is: " + todo.description)
    
    // the todo object is a dictionary
    // so we just access the title using the "title" key
    // so check for a title and print it if we have one
    guard let todoTitle = todo["title"] as? String else {
      print("Could not get todo title from JSON")
      return
    }
    print("The title is: " + todoTitle)
  } catch  {
    print("error trying to convert data to JSON")
    return
  }
}
task.resume()

Example 2: swift get error from the from completion

func asynchronousWork(completion: (inner: () throws -> [String: Any]) -> Void) -> Void {
    URLConnection.sendAsynchronousRequest(request, queue: queue) { 
        (response, data, error) -> Void in
        guard let data = data else { return }
        do {
            guard let result = try JSONSerialization.JSONObjectWithData(data, options: []) 
                as? [String: Any] else {
                completion(inner: { throw OurError.InvalidJSONType })
            }
            completion(inner: { return result })
        } catch let error {
            completion(inner: { throw error })
        }
    }
}

// Call
asynchronousWork { (inner: () throws -> [String: Any]) -> Void in
    do {
        let result = try inner()
    } catch let error {
        print(error)
    }
}