Tony
Tony

Reputation: 12695

AngularJS global error handling - custom method error handler doesn't fire

Here's the scenario (AngularJS v1.3.15):

$httpProvider.interceptors.push(function($rootScope) {
  return {
    'responseError': function(rejection) {          
               //...some custom data checking

               console.log('error #1');
               return rejection;
           }
     };
});

and now, I send the query to the server using the $resource (which returns the 404 error, which is desired in that case), and I return the $promise:

var promise = controller.sendCustomQuery();

promise.catch(function (response) {
                 console.log('error #2');
               }
             );

and in the console I can only see the message error #1 and no error #2. Why ?

Upvotes: 1

Views: 214

Answers (2)

Krzysztof Safjanowski
Krzysztof Safjanowski

Reputation: 7438

Instead of returning rejection itself return rejected promise

angular.module('app', [])
  .config(function($httpProvider) {
    $httpProvider.interceptors.push(function($q) {
      return {
        responseError: function(rejection) {
          console.log('error #1')
          return $q.reject(rejection)
        }
      }
    })
  })
  .run(function($http) {
    $http.get('some/error/path').catch(function() {
      console.log('error #2')
    })
  })
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<div ng-app='app'>

</div>

Upvotes: 1

dfsq
dfsq

Reputation: 193261

Make sure you throw/reject from responseError function:

$httpProvider.interceptors.push(function($rootScope) {
    return {
        responseError: function(rejection) {
            //...some custom data checking
            console.log('error #1');
            throw rejection;
        }
    };
});

If you just return you effectively handle exception (recover) so you will not go to catch in the next step in chain.

Upvotes: 1

Related Questions