2015-01-08 5 views
1

언제 우리의 서버에 성공적으로 사용자가 가입 한,이 같은 200 상태 코드와 JSON 페이로드로 응답어떻게 Restkit에서 사용자 정의 오류 키를 매핑합니까?

{ 
    "error": null, 
    "result": { 
     "auth": { 
      "created_utc": 1420740197, 
      "device_token": "rQZJddrbD5tyEpznb8bVKeGlHqRNGyvOgDR;tQJBkpkfAXO6DQ4lNiG17lzu6IDc0hVBfR3RrN9o0txRQIYAa6fnf5d9LNaSRDMk9LrplgkITuMC37v;;;rvG35CJvV7dWZ5TQVYUWeHwAABvKvzTRpSDw5Qg9jQrmiUHLZptegFY=76421420740197" 
     }, 
     "display_name": "a", 
     "email": "[email protected]", 
     "user_id": 7642, 
     "username": "a" 
    } 
} 

그러나 [email protected]가 다시 가입하려고하면, 그것은 응답 400 상태 코드와이 같은 JSON 페이로드 :

{ 
    "error": { 
     "code": 805, 
     "message": "there is another user with that username" 
    }, 
    "result": null 
} 

나는 Restkit가 오류를 반환 할 때, 나는 메시지뿐만 아니라 코드를 얻을 수 있도록, 오류를 매핑했습니다.

RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]]; 
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"error.message" toKeyPath:@"errorMessage"]]; 

RKResponseDescriptor *errorDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping method:RKRequestMethodAny pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError)]; 

[self.objectManager addResponseDescriptor:errorDescriptor]; 

이 하나가 분명히에만이 출력으로 반환하는 오류의 메시지 부분을 가져옵니다 : 그래서

Error Domain=org.restkit.RestKit.ErrorDomain Code=1004 "there is another user with that username" UserInfo=0x7feefcf8a730 {RKObjectMapperErrorObjectsKey=(
"there is another user with that username" 
), NSLocalizedDescription=there is another user with that username} 

그때 RKErrorMessage의 서브 클래스를 만드는 노력이 내가 그렇게하려고했던 방법이다 :

#import "RKErrorMessage.h" 

@interface TAG_RKErrorMessage : RKErrorMessage 

@property (strong, nonatomic) NSNumber *errorCode; 

@end 

그리고 이것에 매핑 변경 :

RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[TAG_RKErrorMessage class]]; 
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"error.message" toKeyPath:@"errorMessage"]]; 
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"error.code" toKeyPath:@"errorCode"]]; 

하고는 동일한 출력 결과 : 그래서

Error Domain=org.restkit.RestKit.ErrorDomain Code=1004 "there is another user with that username" UserInfo=0x7fa16c627ce0 {RKObjectMapperErrorObjectsKey=(
"there is another user with that username" 
), NSLocalizedDescription=there is another user with that username} 

는 마지막으로 나는 사전의 RKObjectMapperErrorObjectsKey으로 표시 얻을 적어도 노력이 매핑을 시도 NSErroruserInfo :

RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]]; 
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:@"error" toKeyPath:@"errorMessage"]]; 

Error Domain=org.restkit.RestKit.ErrorDomain Code=1004 "<null>" UserInfo=0x7ff8abe678e0 {RKObjectMapperErrorObjectsKey=(
(null) 
), NSLocalizedDescription=<null>} 

가 지금이 시점에서 붙어 :

그리고이 출력 결과 . message뿐만 아니라 두 개의 개별 값으로 반환되는 code에 액세스 할 수 있도록 서버의 오류 응답 키를 매핑하는 방법은 무엇입니까?

답변

3

TAG_RKErrorMessage 인스턴스를 올바르게 매핑했을 가능성이 있습니다. 네가받은 NSError에서 추출하려고 시도 했습니까?를 들어, 당신은 그 배열을 통해 루프가 응답 할 조건에 대해 각 오류를 확인할 수 있습니다

NSArray* objectMapperErrorObjectsArray = [error.userInfo objectForKey:RKObjectMapperErrorObjectsKey]; 

: 모든 매핑 오류 메시지의 배열을 얻을 수있는 NSError의 사용자 정보 사전의 키로 RKObjectMapperErrorObjectsKey을 사용할 수 있습니다 오류 메시지 "잘못된 토큰"와 403 응답 코드에 응답하기를 원한다면 예를 들어, 당신은 할 수 :

NSArray* objectMapperErrorObjectsArray = [error.userInfo objectForKey:RKObjectMapperErrorObjectsKey]; 
for (RKErrorMessage* objectMapperErrorObject in objectMapperErrorObjectsArray) 
{ 
    if ([objectMapperErrorObject.errorMessage isEqual:@"Invalid token"]) 
    { 
     if (operation.HTTPRequestOperation.response.statusCode == 403) 
     { 
      //Code to handle a 403 response status code when error message is "Invalid token". 
     } 
    } 
} 
+1

딱! 한 가지 변경을하고'for (TAG_RKErrorMessage * objectMapperErrorObjectsArray의 objectMapperErrorObject)'를 실행하면 errorCode에 액세스 할 수 있습니다. 도와 주셔서 감사합니다! –

1

그냥 힌트을 : 당신이 내장 된 RKErrorMessage 작성하지 않고 사용하려는 경우 모든 하위 클래스에서 모든 오류 JSON 속성을에 매핑 할 수 있습니다. 이 방법으로:

목표 - C :

RKObjectMapping *errorMapping = [RKObjectMapping mappingForClass:[RKErrorMessage class]]; 
[errorMapping addPropertyMapping:[RKAttributeMapping attributeMappingFromKeyPath:nil toKeyPath:@"userInfo"]]; 

RKResponseDescriptor *errorDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:errorMapping method:RKRequestMethodAny pathPattern:nil keyPath:"error" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassClientError)]; 

스위프트 :

let errorMapping = RKObjectMapping(forClass: RKErrorMessage.self); 
errorMapping.addPropertyMapping(RKAttributeMapping(fromKeyPath: nil, toKeyPath: "userInfo")); 

let errorResponseDescriptor = RKResponseDescriptor(
    mapping: errorMapping, 
    method: RKRequestMethod.Any, 
    pathPattern: nil, 
    keyPath: "error", 
    statusCodes: RKStatusCodeIndexSetForClass(UInt(RKStatusCodeClassClientError))) 
);