Generate your own Error code in swift 3

Rikh picture Rikh · Nov 18, 2016 · Viewed 97.1k times · Source

What I am trying to achieve is perform a URLSession request in swift 3. I am performing this action in a separate function (so as not to write the code separately for GET and POST) and returning the URLSessionDataTask and handling the success and failure in closures. Sort of like this-

let task = URLSession.shared.dataTask(with: request) { (data, uRLResponse, responseError) in

     DispatchQueue.main.async {

          var httpResponse = uRLResponse as! HTTPURLResponse

          if responseError != nil && httpResponse.statusCode == 200{

               successHandler(data!)

          }else{

               if(responseError == nil){
                     //Trying to achieve something like below 2 lines
                     //Following line throws an error soo its not possible
                     //var errorTemp = Error(domain:"", code:httpResponse.statusCode, userInfo:nil)

                     //failureHandler(errorTemp)

               }else{

                     failureHandler(responseError!)
               }
          }
     }
}

I do not wish to handle the error condition in this function and wish to generate an error using the response code and return this Error to handle it wherever this function is called from. Can anybody tell me how to go about this? Or is this not the "Swift" way to go about handling such situations?

Answer

Luca D'Alberti picture Luca D'Alberti · Nov 18, 2016

In your case, the error is that you're trying to generate an Error instance. Error in Swift 3 is a protocol that can be used to define a custom error. This feature is especially for pure Swift applications to run on different OS.

In iOS development the NSError class is still available and it conforms to Error protocol.

So, if your purpose is only to propagate this error code, you can easily replace

var errorTemp = Error(domain:"", code:httpResponse.statusCode, userInfo:nil)

with

var errorTemp = NSError(domain:"", code:httpResponse.statusCode, userInfo:nil)

Otherwise check the Sandeep Bhandari's answer regarding how to create a custom error type