error handling with NSURLConnection sendSynchronousRequest

六眼飞鱼酱① 提交于 2019-11-27 18:50:22
Ben Gottlieb

-sendSynchronousRequest:returningResponse:error: gives you a way to get an error right there in the method itself. That last argument is really (NSError **) error; that is, a pointer to an NSError pointer. Try this:

NSError        *error = nil;
NSURLResponse  *response = nil;

[NSURLConnection sendSynchronousRequest: req returningResponse: &response error: &error];

if (error) {...handle the error}
ohhorob

I would not rely on the error being non-nil to indicate that an error occurred.

I have been using the error checking as described in Ben's answer, but I believe it is generating false-positive / spurious errors in some circumstances.

As per this SO answer, I am changing to use the result of the method to determine success/failure. And then (and only then) check the error pointer for details of the failure.

NSError *requestError;
NSURLResponse *urlResponse = nil;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
/* Return Value
   The downloaded data for the URL request. Returns nil if a connection could not be created or if the download fails.
*/
if (response == nil) {
    // Check for problems
    if (requestError != nil) {
        ...
    }
}
else {
    // Data was received.. continue processing
}

This approach will avoid reacting to an error that occurred in the downloading process that did not cause it to fail. I think it's possible that as the downloading occurs it may encounter non-critical errors that get handled within the framework, and they have the side effect of setting the error pointer with an error object.

For example, I have been getting POSIX errors reported from users that have downloaded the app that seem to have occurred deep in the processing of the URL connection.

This code is used to report the error:

NSString *errorIdentifier = [NSString stringWithFormat:@"(%@)[%d]",requestError.domain,requestError.code];
[FlurryAPI logError:errorIdentifier message:[requestError localizedDescription] exception:nil];

And the error appears reported as:

Platform: iPhone
Error ID: (NSPOSIXErrorDomain)[22]
Msg: Operation could not be completed. Invalid argument

Mapping that back..

requestError.domain = NSPOSIXErrorDomain
requestError.code = 22
[requestError localizedDescription] = Operation could not be completed. Invalid argument

All I've been able to dig up, is that error code 22 is EINVAL, but that hasn't yielded any further details.

Other errors I get are from the NSURL domain, which I totally expect under diverse network conditions:

NSURLErrorTimedOut
NSURLErrorCannotConnectToHost
NSURLErrorNetworkConnectionLost
NSURLErrorNotConnectedToInternet
+others
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!