Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire doesn't catch error

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.

like image 238
Azuan Avatar asked Jun 27 '26 00:06

Azuan


1 Answers

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.

like image 148
Azuan Avatar answered Jun 28 '26 15:06

Azuan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!