当响应状态码不是 2xx 时,将调用失败块,您可以在那里捕获自定义错误,打开operation.HTTPRequestOperation.response.statusCode
如果您想使用 RestKit 处理错误,以更通用的方式,您可以考虑向您的 RKObjectManager 添加所有 4xx 和 5xx 错误的响应描述符 - 在本例中,我将使用此主体结构映射错误
{"errorCode":"996","errorMessage":"This is my custom error message"}
配置你的 RKObjectManager:
RKObjectMapping* errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"errorMessage" toKeyPath:@"errorMessage"]];
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"userInfo"]];
NSIndexSet *clientErrorStatusCode = RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError); // Any response in the 4xx
NSIndexSet *serverErrorStatusCode = RKStatusCodeIndexSetForClass(RKStatusCodeClassServerError); // Any response in the 5xx
RKResponseDescriptor *clientErrorDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"" statusCodes:clientErrorStatusCode];
RKResponseDescriptor *serverErrorDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping method:RKRequestMethodAny pathPattern:nil keyPath:@"" statusCodes:serverErrorStatusCode];
//... Remember to add response descriptors to your object manager
然后在请求的失败块中,您可以打开状态代码并处理错误:
failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKErrorMessage *errorMessage = [[error.userInfo objectForKey:RKObjectMapperErrorObjectsKey] firstObject];
NSString *errorCode = [errorMessage.userInfo objectForKey:@"errorCode"];
if (operation.HTTPRequestOperation.response.statusCode == 304){
//Handle your 304 error
}
}