Restkit json error response msg from server

后端 未结 4 756
暖寄归人
暖寄归人 2020-12-28 18:50

I have used many hours on how to solve this issue. Im using Restkit 0.9.3 with Object Mapping 2.0. All data is in JSON. I can make GET, POST, PUT and DELETE operations corre

4条回答
  •  春和景丽
    2020-12-28 19:26

    For RestKit v0.20

    assuming your HTTP body is:

    {"error": "..."}
    

    you create an the mapping and descriptor:

    RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]];
    
    [errorMapping addPropertyMapping: [RKAttributeMapping attributeMappingFromKeyPath:@"error" toKeyPath:@"errorMessage"]];
    RKResponseDescriptor *errorResponseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError)];
    [objectManager addResponseDescriptor:errorResponseDescriptor];
    

    and then you can access it from your failure block:

    failure:^(RKObjectRequestOperation *operation, NSError *error) {
                    NSLog(@"errorMessage: %@", [[error userInfo] objectForKey:RKObjectMapperErrorObjectsKey]);
                }
    

    This uses the built-in RKErrorMessage class, though you can create your own custom class with additional fields.

提交回复
热议问题