[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 网络调用中处理错误/数据处理的正确方法吗?
如果http状态码不是200,我们是否总是假设来自异步请求的NSError总是非零,如果它是200,则总是零?