Search code examples
iosswiftalamofire

compare error object return by alamofire


I'm using Alamofire with EVReflection, in case responseObject fails to parse the raw response string into an object, an response.error will have some value, in case of a different error, a different value will be set.

Not sure how to compare those error values, to handle different error.

in case of JSON parsing error, print(error) will output

FAILURE: Error Domain=com.alamofirejsontoobjects.error Code=1 "Data could not be serialized. Input data was not json." UserInfo={NSLocalizedFailureReason=Data could not be serialized. Input data was not json.}

Alamofire.request(...)           
            .responseObject { (response: DataResponse<UserData>) in
                guard response.error == nil else {
                    print(response.error)
                    return
                }
             }

Solution

  • When your request fails, you will get an error of type AFError from Alamofire. You can actually check AFError.swift file to get familiar with possible values. This file have really good documentation for every case.

    Since AFError is an Error, which is of type enum, you can check like following:

    switch err {
    case .parameterEncodingFailed(let reason):
        // do something with this.
        // If you want to know more - check for reason's cases like
        // switch reason {
        // case .jsonEncodingFailed(let error):
        //     … // handle somehow
        // case .propertyListEncodingFailed(let error):
        //     … // handle somehow
        // }     
    case .responseValidationFailed(let reason):
        // do something else with this
    …
    }
    

    And for every reason you have some helper functions, so you can get even more info. Just check documentation.