當用戶在我們的服務器上籤約成功,它以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
的NSError
的userInfo
:
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>}
現在我被困在這一點上。如何映射服務器錯誤響應的密鑰,以便我可以訪問返回的code
以及message
作爲兩個單獨的值?
完美!要做一個改變,併爲'(TAG_RKErrorMessage * objectMapperErrorObjectsArray中的objectMapperErrorObject)'執行''所以我可以訪問errorCode。謝謝您的幫助! –