【问题标题】:RestKit Mapping with unsuccessful status codes带有不成功状态代码的 RestKit 映射
【发布时间】:2013-05-29 09:54:03
【问题描述】:

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

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

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

最好的问候, 迈克尔

【问题讨论】:

    标签: ios mapping restkit-0.20


    【解决方案1】:

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

    [[[operation.error userInfo] objectForKey: RKObjectMapperErrorObjectsKey] firstObject];
    

    【讨论】:

    • 这对我有用。此外,您的映射将被应用,您可以获得正确映射的对象。
    【解决方案2】:

    当响应状态码不是 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
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      • 1970-01-01
      • 1970-01-01
      • 2012-10-14
      • 1970-01-01
      相关资源
      最近更新 更多