3

我正在尝试将 403 禁止响应映射到自定义对象。我使用响应代码注册了一个映射,如下所示:

RKResponseDescriptor* tacResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:termsAndConditionMapping pathPattern:@"user" keyPath:nil statusCodes:[NSIndexSet indexSetWithIndex:403]];
[objectManager addResponseDescriptor:tacResponseDescriptor];

但是当403从服务器发送响应时,我只是Non-successful status code encountered: performing mapping with nil target object从 RestKit 获得一个 ' ' 日志,并使用操作的mappingResult属性执行失败块nil。我在这里做错了什么?我需要将特定路径的一个特定错误案例映射到特定对象。

最好的问候,迈克尔

4

2 回答 2

1

我不完全确定您的意思,但是如果您最终进入失败块,则没有 mappingResult 属性。但是可以发现该错误隐藏在operation属性中:

[[[operation.error userInfo] objectForKey: RKObjectMapperErrorObjectsKey] firstObject];
于 2013-12-12T09:30:42.630 回答
0

当响应状态码不是 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
    }
}
于 2015-03-03T17:18:58.230 回答