[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
NSDictionary * dictionary = nil;
NSError * returnError = nil;
NSString * errorCode = nil;
NSString * errorText = nil;
NSInteger newErrorCode = 0;
if([data length] >= 1) {
dictionary = [NSJSONSerialization JSONObjectWithData: data options: 0 error: nil];
}
if(dictionary == nil) {
newErrorCode = -1;
errorText = @"There was an unexpected error.";
NSMutableDictionary* details = [NSMutableDictionary dictionary];
[details setValue: errorText forKey: NSLocalizedDescriptionKey];
returnError = [NSError errorWithDomain: AppErrorDomain code: newErrorCode userInfo: details];
responseHandler(nil, returnError);
return;
}
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
if(statusCode != 200)
{
if(dictionary != nil) {
if([dictionary objectForKey: @"error_code"] != nil) {
errorCode = [dictionary objectForKey: @"error_code"];
}
if([dictionary objectForKey: @"error_description"] != nil) {
errorText = [dictionary objectForKey: @"error_description"];
}
}
if(errorCode == nil)
{
newErrorCode = UnexpectedError;
errorText = NSLocalizedString(@"There was an unexpected error.", @"There was an unexpected error.");
}
else {
newErrorCode = [errorCode intValue];
}
NSMutableDictionary* details = [NSMutableDictionary dictionary];
[details setValue: errorText forKey: NSLocalizedDescriptionKey];
returnError = [NSError errorWithDomain: APPErrorDomain code: newErrorCode userInfo: details];
}
responseHandler(dictionary, returnError);
return;
}];在上面的异步网络调用中,我检查状态代码是否不是200,并假设这是一个错误。这是处理IOS中网络调用中的错误/数据处理的正确方法吗?
我们是否可以总是假设来自异步请求的NSError总是非nill (如果http状态代码不是200 ),而nill(如果不是200 )?
发布于 2013-10-11 18:31:08
据我所知,如果您的NSURLConnection返回一个错误,这意味着没有收到来自服务器的响应。
如果服务器发送它的响应,不管是什么HTTP代码,NSUrlConnection都不会给出任何错误(返回的错误为零)。
实际上,NSURLError.h列出了与NSURLConnection相关的所有错误,这些错误可以是:
NSURLErrorTimedOut
NSURLErrorCannotConnectToHost
NSURLErrorNetworkConnectionLost
NSURLErrorNotConnectedToInternet因此,您可以在从网络调用中收到的NSError对象中找到这类错误。
相反,如果您有一个HTTP错误,这意味着至少可以到达服务器,它的答复,等等。
您还可以在网络分层体系结构的上下文中看到这一点,其中HTTP是应用程序协议,HTTP错误仅在该级别有意义。
另一方面,NSURLConnection工作在传输级别,低于应用程序级别。因此,应用程序级别的错误对它没有任何意义,只是透明地从一端“传输”到另一端。
https://stackoverflow.com/questions/19324357
复制相似问题