swift call a function that throws error code example

Example: swift create a method who can return result or throw an error

class SecurityService {
  static func loginWith(email: String, password: String, callback: (error: NSError?, user: User?) -> Void) -> Void {

    let URL = ".."
    let params = [
      "email": email,
      "password": password
    ]

    HTTP.request(URL, method: "POST", params: params) { (error, result) in
      if let error = error {
        callback(error: error, user: nil)
      } else {
        guard let JSON = result else {
          let someDomain = "some_domain"
          let someCode = 100
          let someInfo = [NSLocalizedDescriptionKey: "No results were sent by the server."]

          let error = NSError(domain: someDomain, code: someCode, userInfo: someInfo)
          callback(error: error, user: nil)
          return
        }

        guard let name = JSON["name"] as? String, email = JSON["email"] as? String else {
          let someDomain = "some_domain"
          let someCode = 100
          let someInfo = [NSLocalizedDescriptionKey: "No user properties were sent by the server."]

          let error = NSError(domain: someDomain, code: someCode, userInfo: someInfo)
          callback(error: error, user: nil)
          return
        }

        let user = User(name: name, email: email)
        callback(error: nil, user: user)
      }
    }
  }
}