Alamofire Parse Response Data when validate fails
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.
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))")
})