How to make webservice pass errors through NSURLConnection's connection:didFailWithError:?
ios, nsurlconnection, web-services
Solution
In my experience (the three most dangerous words in programming), `-connection:didFailWithError:` is only called if the HTTP exchange failed. This is usually a network error or maybe an authentication error (I don't use authentication). If the HTTP message succeeds, no matter the response code, `-connectionDidFinishLoading:` is called.
My solution: call `-connection:didFailWithError:` when I detected an error. That way all my error handling code is in one place.
At the top of my `-connectionDidFinishLoading:`, I have:
NSError *error;
NSDictionary *result = [self parseResultWithData:self.connectionData error:&error];
if (!result) {
[self connection:connection didFailWithError:error];
return;
}
Problem
What does a web service need to do to cause `NSURLConnection's` delegate to receive the `connection:didFailWithError:` message? For example: iOS app passes a token to the web service, web service looks up the token, and then the web service needs to respond with an error saying "invalid token" or something of the like. Currently, the data is received, and in "`connectionDidFinishLoading`:" is parsed for error messages. This means I'm error checking in two places, which I am trying to avoid. I have both the iOS app and web service completely under my control.