1

Is there a good way to catch errors in Angular regarding connection problems?

Service $http POST:

    dossierService.getDossier(uid)

    .then(function (result) {

        vm.dossier = result.dossier;

    }, function (error) {

        handleError(error)

    });//end dossierService.getDossier(uid)

If there is a connecting problem it will return an error:

POST http://192.168.25.1:8080/api/query net::ERR_CONNECTION_TIMED_OUT

How can I show the correct message to the user letting him/her know what the exact error is?

3

2 Answers 2

1
$http.post("/path", {data:"data"}).then(function(response){
    // do something with success response
}).catch(function(error) {

  console.log(JSON.stringify(error));
  $scope.myerror=error

});

and in your view ...

<div ng-if="myerror!=null">
    {{myerror}} OR {{myerror.message}}
</div>
Sign up to request clarification or add additional context in comments.

Comments

1

You can create an object with the http response codes and link a message. To throw these errors you can use an interceptor.

moduleError.factory('HttpErrorHandler', function (){
    return {
        401: 'You are not logged in',
        403: 'You do not have permissions'
    }
});



$httpProvider.interceptors.push(function($q, HttpErrorHandler) {
  return {
   'responseError': function(rejection) {
      console.log(HttpErrorHandler[rejection.status]);
  };
});

If the error is related to this operations, launch errors where you are launching. You can throw the code 400 for your errors with a object in the body like:

{
   code: 30002, //Thats your custom code
   message: 'My custom error message'
}

.

dossierService.getDossier(uid)

.then(function (result) {

    vm.dossier = result.dossier;

}, function (error) {

    if(error.status == 400){
      var my_error = JSON.parse(error.data);
      console.log(my_error.message);
    }

});

I think this is a good aproach.

1 Comment

i think this is a good answer but badly explained lol. Please explain where you would access the error object, possibly using a console.log statement to do so. Also I believe this is meant to be a generic approach to handle ALL http errors without having to handle them inside a promise rejection every time. Please confirm Serginho

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.