Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire Parse Response Data when validate fails

Tags:

alamofire

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

like image 532
Tobias Avatar asked Sep 05 '16 02:09

Tobias


2 Answers

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.

like image 172
cnoon Avatar answered Nov 23 '22 23:11

cnoon


Swift 4

If you get an error, you can try parsing the response data as a string or as json.

import Alamofire
import SwiftyJSON

Alamofire.request("http://domain/endpoint", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil)
    .validate()
    .responseJSON(completionHandler: { response in
        if let error = response.error {
            if let data = response.data {
                if let errorString = String(bytes: data, encoding: .utf8) {
                    print("Error string from server: \(errorString)")
                } else {
                    print("Error json from server: \(JSON(data))")
                }
            } else {
                print("Error message from Alamofire: \(error.localizedDescription)")
            }

        } 
        guard let data = response.result.value else {
            print("Unable to parse response data")
            return
        }
        print("JSON from server: \(JSON(data))")
    })
like image 36
Derek Soike Avatar answered Nov 24 '22 01:11

Derek Soike