Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is Angular $http service callback ignored?

In my Angular app, I have the following code that calls an API with success and error callback functions

    $http.post('/analytics/generateToken', {}).then(
      function (data) {
        console.log("Success");
      },
      function (data) {
        console.log("Error");
      }
    );

The success callback is invoked when the API call returns a HTTP 200 status, but neither callback is invoked when the API call returns a HTTP 403 (forbidden) error status. Why is the error callback not invoked in this case?

like image 730
ivanhoe Avatar asked Mar 25 '26 03:03

ivanhoe


1 Answers

It is working for me on Chrome Version 44.0.2403.52 beta (64-bit);

Make sure that you have not set an Interceptor that avoid the error callback to be executed.

A Interceptor should return a Promise rejection as pointed in the Angular documentation, if it does not return it, the error callback is not going to be executed.**

 'responseError': function(rejection) {
      if (canRecover(rejection)) {
          return responseOrNewPromise;
          //in this case the error callback is not executed
      }

      return $q.reject(rejection);
  }

Also you can consider to use the .catch() instead of the second argument in order to follow the Promise standard. That method is executed when the Promise is rejected or throw an error ($http.post return a Promise) ;

$http.post('/analytics/generateToken', {}).then(
    function (result) {
         console.log("Success");
     },
).catch(
    function(error) {
       console.log("error");    
    }
);
like image 132
ecarrizo Avatar answered Mar 26 '26 16:03

ecarrizo