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?

marlonlaan
  • 127
  • 1
  • 2
  • 10

2 Answers2

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.

Serginho
  • 7,291
  • 2
  • 27
  • 52
  • 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 – danday74 Jan 20 '16 at 10:31
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>
danday74
  • 52,471
  • 49
  • 232
  • 283