2

In Alamofire calling .validate() does automatic validation and passes status code 200...299 as success.

In case of failed API request server sends status code 400 and some internal error message and code in JSON to identify which kind of error is this. I couldn't find a way to get this JSON data in case status code is 400 under case .Failure in following example:

Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
         .validate()
         .responseJSON { response in
             switch response.result {
             case .Success:
                 print("Validation Successful")
             case .Failure(let error):
                 print(error)
             }
         }

error doesn't contain response data. Is there anyway to get it?

Sharjeel
  • 15,588
  • 14
  • 58
  • 89
  • Uhm.. interesting I cross with a problem like that before in which the server was not implemented using the conventional ways and I have to validate manually myself, the thing is that maybe even when it's an error could have data about the error in the JSON returned and in this case the error could be empty – Victor Sigler Aug 04 '16 at 16:55
  • @VictorSigler Server is implemented correct. Example: Let's say it's login request. If the user is logged-in then statusCode is 200 but if user isn't logged-in then statusCode is 400 with JSON response explaining why user isn't logged-in (invalid password, account expired etc) – Sharjeel Aug 04 '16 at 17:03
  • 1
    Yes is exactly what I said above, in this case I'm afraid you can't use the `validate()` of Alamofire and you should try to use in the response the `statusCode` and try to filter cases like I did in the past for this crazy API :) – Victor Sigler Aug 04 '16 at 17:05
  • 1
    Please see the answer here http://stackoverflow.com/a/35324741/5093900 – phantom_2 Nov 30 '16 at 15:21

1 Answers1

0

If there is json data returned from the server on error, you should be able to get it from the response object, like:

print(response.result)   // result of response serialization

if let JSON = response.result.value {
    print("JSON: \(JSON)")
}

You can also subclass the ErrorType object returned by Alamofire:

public enum BackendError: ErrorType {
    case Network(error: NSError)
    case DataSerialization(reason: String)
    case JSONSerialization(error: NSError)
    case ObjectSerialization(reason: String)
    case XMLSerialization(error: NSError)
}

This will give you more information about the error if you dont want to construct a custom error object to return. More on this from the Alamofire docs: https://github.com/Alamofire/Alamofire#handling-errors

DTHENG
  • 188
  • 1
  • 7