Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire: handle error with success response

Hi i am still new to Alamofire and json. i just want to ask on how to handle error on success response. Below is the response of the api with post request.

{
data =     {
    "cabinet_id" = 3289146811;
    "created_at" = "2018-04-11T04:53:43.288023001Z";
    "user_id" = 123abc;
};
}

but sometimes i got response as below due to server error

{
error =     {
    "http_status_code" = 400;
    message = "Unable to proceed";
    type = "rent_request_failed";
};
}

here is what i have did

let url = "myurl"
let parameters = ["user_id": ""\(self.idPassed)"",
                          "cabinet_id": "\(self.stringPassed)"]

        Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).responseJSON { response in

                if (response.result.isSuccess){

                    if let value = response.result.value {
//now success or failed always navigate to here                            
Helper.helper.switchToNavigationViewController(Navigation: "hundredpercent")
                        print(value)

                    }
                //do your json stuff
                } else if (response.result.isFailure) {
                //Manager your error
                switch (response.error!._code){
                case NSURLErrorTimedOut:
                //Manager your time out error
                break
                case NSURLErrorNotConnectedToInternet:
                //Manager your not connected to internet error
                break
                default:
                    let alertt = UIAlertController(title: "Server Error!", message: "Please try again", preferredStyle: .alert)

                    alertt.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: {(action:UIAlertAction!) in
//need navigate here if error                        
Helper.helper.switchToNavigationViewController(Navigation: "qrcodescan")

                    }))

                    self.present(alertt, animated: true)
                }
                }
        }
like image 520
madhatter989 Avatar asked Apr 11 '18 05:04

madhatter989


2 Answers

Validate the response status code while calling API by adding validate(statusCode: 200..<299) on alamofire request.

It will validate to success if your http status code lies in interval 200-299 otherwise it go into failure case.

        // Call response handler method of alamofire
        Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding.default).validate(statusCode: 200..<299).responseJSON(completionHandler: { response in

            switch response.result {
            case .success(let data): 
                Logs.DLog(object: "\n Success: \(response)")

                // Do your code here...

            case .failure(let error):
                Logs.DLog(object: "\n Failure: \(error.localizedDescription)")

                // Do your code here...

            }
        })
like image 135
Ankit Jayaswal Avatar answered Oct 06 '22 23:10

Ankit Jayaswal


This is a way that I used handle the responce. Hope this will help you.

class func Request(statusCallBack: @escaping (_ statusCode: Int) -> Void, successCallback: @escaping (_ result: AnyObject) -> Void, errorCallback: @escaping (_ error: Error) -> Void) {

Alamofire.request(url, method: method, parameters: params, encoding: encodingType, headers: headers).responseJSON { (responce) in

        // Here checking the status code of response
        if let status = responce.response?.statusCode {
            if status == 401 && AppUserDefault.getAccessToken() != nil {
                User.logout()
                return
            }
            statusCallBack(status)
        }
        switch responce.result {
        case .success(_):
            if let result = responce.result.value {
                successCallback(result as AnyObject)
            } else {
                errorCallback(NSError(domain: "Internal server error", code: 1002, userInfo: nil))
            }
            break
        case .failure(let error) :
            errorCallback(error)
            break
        }
    }
}
like image 43
isuru madusanka Avatar answered Oct 06 '22 22:10

isuru madusanka