3

What's the best way to create an NSError object based on a standard HTTP status code (ideally one which includes some human-readable message in the localizedDescription)? Is there a standard method or should I just create my own error domain to use with NSError?

devios1
  • 36,899
  • 45
  • 162
  • 260
  • Related: http://stackoverflow.com/questions/1779034/nserror-domains-custom-domains-conventions-and-best-practices?rq=1 – rmaddy Apr 27 '15 at 23:15

1 Answers1

2

Foundation's objects for performing network requests will often return these NSErrors for you. NSURLConnection, for example, will provide an NSError in the completionHandler of its +sendAsynchronousRequest:queue:completionHandler: method.

If you'd like to roll your own you could create an instance of an NSError, set its error domain to be NSURLErrorDomain, set its code to be the HTTP status code you want, and set its localizedDescription to be the human readable string you need.

Tim Johnsen
  • 1,471
  • 14
  • 33
  • 1
    Seems to me adding my own error codes to a domain I don't control is a bad idea. – devios1 Apr 30 '15 at 19:08
  • Yeah, you could also have your own error domain, that probably doesn't answer your question of having stock NSURLErrors – Tim Johnsen Apr 30 '15 at 19:21
  • When the connection succeeds and the server responds with an error code, the `NSError?` passed to the `completionHandler` is `nil`. – ma11hew28 May 12 '16 at 14:08
  • I'd like it if this answer was right, but it seems to be wrong. The most obvious status codes I checked -- 404 and 500 -- don't return any `NSError` at all, just `nil`. – Chris Burt-Brown Jun 29 '16 at 12:38
  • this is incorrect - NSError will only be created if the NETWORKING layer has failed. If networking succeeded, and server sent, say, 402 status, no NSError will be created. I am looking for such code to build a robust NSError representations for the plenty http status scenarios, for a long time now. – Motti Shneor Feb 19 '20 at 11:46