Search code examples
alamofire

Alamofire Parse Response Data when validate fails


So the API I'm working with will sometimes send an error message in the response body when a request fails. This is located in response.data. Sometimes it's JSON, sometimes it's a string. I'm using the validate method so result.value is nil when an error occurs.

Is there a way of having Alamofire serialize the data from NSData to a string or for JSON to [ String : AnyObject ] like it would if the response was successful?

I would like to keep using the validate method.

EDIT: Here's a link to a feature request I started on the Alamofire GitHub project.

https://github.com/Alamofire/Alamofire/issues/1459


Solution

  • There is not currently. I'm actually working on this very feature in Alamofire 4 right now. In Alamofire 3, you'll have to parse the response.data yourself if you get that validation error. In Alamofire 4, you'll at least have access to the response.data at the time of validation as well as be able to customize the Error that is generated by validation.

    Most likely what the final solution will be is the ability to check in validation if you know there's going to be an error (checking response status code and headers). Then based on the type of error, you could parse the response.data to extract the error message from the server and throw a VERY SPECIFIC error from validation. This is most likely what the new system will allow. This way you could identify OAuth2 access token errors right in validation and throw your own custom error rather than having to use a convoluted system of response serializers to do it.