3

I am struggling to get the json error message returned using Alamofire and their .success / .failure method.

Before using this I could use response.result.value and get the returned error message but now I am validating the status code .validate(statusCode: 200..<300).

Have tried several things to receive the error but it always produces nil or just the status code.

 Alamofire.request(url, method: .post, parameters: body, encoding: JSONEncoding.default)
            .validate(statusCode: 200..<300)
            .responseJSON { response in
                switch response.result {            
                case .success:
                    //Other stuff
                case .failure(let error): 
                    print(response.result.value) //Produces nil when there is an error
                    print(error.localizedDescription)
                    print(response.result.error.customMirror)
                    print(response.result.error.debugDescription)
                    print(response.result.error.unsafelyUnwrapped)
                    print(response.result.error?.localizedDescription)
                }
        }

How can I get the error json? It is getting returned as such.

{
  "status": "error",
  "message": "Incorrect Password"
}
Allreadyhome
  • 1,252
  • 2
  • 25
  • 46
  • What do you get in the output using print(response.result.error.debugDescription)? – Alex McPherson Jan 30 '17 at 11:08
  • @AlexMcPherson `Alamofire.AFError.responseValidationFailed(Alamofire.AFError.ResponseValidationFailureReason.unacceptableStatusCode(404)` – Allreadyhome Jan 30 '17 at 11:13
  • Which is a bit weird because the API produces a 403 – Allreadyhome Jan 30 '17 at 11:15
  • well a 404 is Not Found so thats odd. – Alex McPherson Jan 30 '17 at 11:18
  • in fact it does return a 403 if I enter the full information! Still doesn't pick up the json though which is frustrating. Wanted to use this method to keep it clean. – Allreadyhome Jan 30 '17 at 11:21
  • Well you are getting a 403 Not Authorised and your Json states that you're using an incorrect password no? Does this help you? http://stackoverflow.com/questions/29131253/swift-alamofire-how-to-get-the-http-response-status-code – Alex McPherson Jan 30 '17 at 11:25
  • The issue is I can't access the json message just the status code. I know the json message is getting returned as if I remove the `.validate` I can get it with `result.value` but its nil otherwise. The error reporting from the example you linked to just produces `Response validation failed: Response status code was unacceptable: 403` – Allreadyhome Jan 30 '17 at 11:33

1 Answers1

2

take that .validate() out. You will see more detailed description.

Arafin Russell
  • 1,487
  • 1
  • 18
  • 37