Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate your own Error code in swift 3

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?

like image 592
Rikh Avatar asked Nov 18 '16 07:11

Rikh


People also ask

How can a function throw an error in Swift?

Sometimes functions fail because they have bad input, or because something went wrong internally. Swift lets us throw errors from functions by marking them as throws before their return type, then using the throw keyword when something goes wrong.

What is error in Swift?

In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling.

What is made up of NSError object?

The core attributes of an NSError object are an error domain (represented by a string), a domain-specific error code and a user info dictionary containing application specific information.


1 Answers

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

like image 166
Luca D'Alberti Avatar answered Oct 13 '22 21:10

Luca D'Alberti