Handling error when no data is returned (AngularJS)

0

From the question: link How do I handle the error when I can not find the zip code?

Look at the error that it returns, I wanted it to return an alert when it gives this error:

XMLHttpRequest cannot load http://api.postmon.com.br/cep/053140010. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 404.

    
asked by anonymous 12.11.2015 / 02:02

1 answer

2

Response code you mentioned as a reference :

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script><script>angular.module('app',[]);angular.module('app').controller('MyCtrl',functionMyCtrl($http,$scope){$scope.busca=function(){$http.get('http://api.postmon.com.br/cep/'+$scope.cep).success(function(local){$scope.local_encontrado=local;console.log(local);});};$scope.enter=function(e){if(e.keyCode==13){$scope.busca();};};});</script>

Noticethattheexampleusesonlythesuccessmethod,thatis,whenitreturnsnoerror,andtheresponsestatusis2**,usually200.Sowhat'smissing?Itisnecessarytomentionanothermethodcallederror,withtheintentionoftreatingwhenacertainerroroccurs,liketheoneyoumentioned,seehowthecodeis:

Codechangehandlingerrors:

<linkrel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.js"></script><script>angular.module('app',[]);angular.module('app').controller('MyCtrl',functionMyCtrl($http,$scope){$scope.busca=function(){$http.get('http://api.postmon.com.br/cep/'+$scope.cep).success(function(local){$scope.local_encontrado=local;console.log(local);}).error(function(e){alert("Erro ao carregar CEP");
            });
        };

        $scope.enter = function(e){
            if(e.keyCode == 13){
                $scope.busca();
            };
        };
    });
</script>

In the body of the code I insert the function error so that when a certain error occurs, it shows an alert for the user to know what happened, this method will usually be called when a status of an HTTP response is 4** or 5** .

This will treat the errors as the error you mentioned, but if you do not find a particular zip code refer to the API documentation that you are using to verify your return. Even if you do not find the zip code, it will fall within success to handle this information, it will not fall within error because it was a successful request, right?

References :

link

link

    
12.11.2015 / 12:24