[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則是否爲nill?
如果我沒有弄錯,如果發生錯誤,completionHandler的NSError將爲非NULL。從那裏你可以得到相關的錯誤代碼,域和描述。如果NSError不是NULL,那麼你可以檢查它是從那裏繼續的代碼。 – Jonathan