3

I'm using Alamofire for my http requests but I'm not able to get error message from requests that don't pass validation

Alamofire.request(method, url, headers: headers, parameters: parameters, encoding: encoding)
            .validate(statusCode: 200..<300)
            .responseJSON { response in

                switch response.result {
                case .Success:
                    // response.result.value returns JSON

                case .Failure(let error):
                    // response.result.value returns nil
                }
        }

How can I get data (JSON) if I get error code 400 and others. The API is sending the data in body even if the request was not successful.

Stevik
  • 1,092
  • 2
  • 16
  • 37

2 Answers2

3

As Following SaiCYLi, Only way to get response data is avoid using validate.
See Result.swift in Alamofire.
There is blocker.

public var value: Value? {
    switch self {
    case .Success(let value):
        return value
    case .Failure:
        return nil
    }
}

I wanted comment to you instead of answering. But I have reputation less than 50. Sorry.

Yuki Sato
  • 31
  • 1
2

just delete your validation of status code

Code:

Alamofire.request(method, url, headers: headers, parameters: parameters, encoding: encoding)
      .responseJSON { 
      response in
            let statusCode = response.response.statusCode
            switch statusCode {
            case 200..<300:
                // Success
            case 404:
                // not found
            default: 
                // something else
            }
    }
Sai Li
  • 685
  • 6
  • 14