0

I have a protocol that contains two functions successWeather and errorWeather. When the status code returns something other than 200-299 I want it to throw the errorWeather function.

My question is: How can I force an error if the guard catches the status code? As of now, error returns nil.

func errorWeather(error: NSError)

let task = URLSession.shared.dataTask(with: request) { (data, response, error) -> Void in
        if let error = error {
            self.delegate.errorWeather(error: error as! NSError)
        }

        guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
            print("Your request returned a status code other than 2xx!")
            //How can I force an error?
            return
        }
Casey
  • 164
  • 4
  • 16
  • It is kind of unclear -at least for me-, what's the relationship between the protocol and the throwable function? could you elaborate? – Ahmad F Apr 08 '17 at 19:54
  • I basically created it as a delegate system to use the api. In a detailView it conforms to the protocol and has to use successWeather and errorWeather. @AhmadF – Casey Apr 08 '17 at 20:01
  • So, -if I got it right- what's the purpose of implementing both delegate and throwable function? I suggest to let it be only one option to handle the error. Is the problem of how you should implement the delegate or the throwable function? Also, you might want to check [this Q&A](http://stackoverflow.com/questions/40501780/examples-of-delegates-in-swift-3/40503024#40503024). – Ahmad F Apr 08 '17 at 20:06
  • 1
    @Casey could you check my answer – Nazmul Hasan Apr 08 '17 at 20:15
  • I recommend the Swift way: a callback closure returning an enum adopting the `Error` protocol with associated values. – vadian Apr 08 '17 at 20:24

1 Answers1

1

An NSError object encapsulates information about an error condition in an extendable, object-oriented manner. It consists of a predefined error domain, a domain-specific error code, and a user info dictionary containing application-specific information. more check Apple Doc

 guard let statusCode = (response as? HTTPURLResponse)?.statusCode, statusCode >= 200 && statusCode <= 299 else {
                print("Your request returned a status code other than 2xx!")
                //How can I force an error?
                let error = NSError(domain: "statusCode",
                              code: (response as? HTTPURLResponse)?.statusCode,
                          userInfo: [NSLocalizedDescriptionKey: "Your request returned a status code other than 2xx!"])

                    self.delegate.errorWeather(error: error )
                return
            }
Nazmul Hasan
  • 10,130
  • 7
  • 50
  • 73