Restkit json error response msg from server

后端 未结 4 767
暖寄归人
暖寄归人 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:35

    Using Restkit v0.2x you can map all JSON attributes you want to the already existing RKErrorMessage.userInfo Dictionary property in this [Swift] way:

    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", //or nil, according to your json response
        statusCodes: RKStatusCodeIndexSetForClass(UInt(RKStatusCodeClassClientError)))
    );
    

    So, you can map an error JSON response like this one:

    {
        "error": {
            "message": "Error message",
            "cause": "...",
            "code": "my_error_code",
            "url": "..."
            ...
        }
    }
    

    And retrieve the RKErrorMessage with all attributes, in a failure closure, as follows:

    failure: { (operation, error) -> Void in
        if let errorMessage = error.userInfo?[RKObjectMapperErrorObjectsKey]?.firstObject as? RKErrorMessage{
            let message = errorMessage.userInfo["message"] as! String;
            let code = errorMessage.userInfo["code"] as! String;
            ...
        }
    }
    

    I hope this can be helpful to someone!

提交回复
热议问题