Alamofire doesn't catch error

2.8k Views Asked by At

I'm using Alamofire to get data from my server. However, it doesn't catch the error, as the error returned is nil. I've tested with AFNetworking, and it works fine. For both operation, the status code returned is 401 Unauthorized . Is there's something with my code?

I'm using GrapeAPI for my backend. All it does is just to return the error on fail request

GrapeAPI

error!('Unauthorized', 401)

AFNetworking

manager.GET("someUrl", parameters: nil, success: { (_, object) in

        }, failure: { (operation, error) in
            // These are the outputs. I'm not assigning any values
            // error.localizedDescription = "Request failed: unauthorized (401)"
            // statusCode = 401
        })

Alamofire

Alamofire.request(.GET, "url", parameters: nil)
        .response { (a,b,data,error) in
        // These are the outputs. I'm not assigning any values
        // error = nil
        // data = {"error":"Unauthorized"}
        // statusCode = 401
        }

I can check the failure using the statusCode. But I prefer to check the error object instead. However, since the error is nil in Alamofire, it's quite confusing to check whether the request has failed or not.

2

There are 2 best solutions below

0
On BEST ANSWER

As Matt has mentioned in the comment, I need to add .validate() before calling .response(). This is by design. Final code as below:

Alamofire.request(.GET, "url", parameters: nil)
    .validate()
    .response { (a,b,data,error) in
    // error won't be nil now
    // and statusCode will be 401
    }

Read this detailed explanation(thanks!) for more information.

1
On

Alamofire does not see 401 Unauthorized as an error as it is an valid return. In your comment code you are assigning a value to error not checking it for error, it should be:

Alamofire.request(.GET, "url", parameters: nil)
        .response { (a,b,data,error) in
        if error != nil{
            println(error.localizedDescription)
        } else {
            if let data = data{
               //You should probably use a switch statement here
               if data.statusCode == 401 {
                   println("Unauthorized")
               } else if data.statusCode == 200 {
                   println("Success")
               }
           }
        }

I am not sure if i understand correctly your problem, but I hope that help!