Mukund Gandlur
Mukund Gandlur

Reputation: 869

Javascript http get success function capturing error response

I am making a http request to a url which is returing a 500 error response(This is the expected behavior). But this is error is getting captured in the success function instead of error function.

$http.get("myUrl")
    .then(function (response) {
        console.log(response);
    }
    .function (error) {
        // Handle error here
    });

Please help in understanding this and the correct way to use this.

Upvotes: 1

Views: 102

Answers (3)

Mukund Gandlur
Mukund Gandlur

Reputation: 869

I had an interceptor in my application which was causing the problem. All my error responses were intercepted and returned without a status. Below is the code.

return {
        'responseError': function(config) {

            if(config.status===401){
              //Do Something

              return config;
            }

          return config;
        }
    }

Changing the return statement to return $q.reject(config); started returning the correct status.

Upvotes: 0

jpdombrowski
jpdombrowski

Reputation: 11

If this is angulars $http, it's supposed to be something like this:

$http.get("myUrl")
  .then(
    function (response) {
      console.log(response);
    },
    function (error) {
      // Handle error here
    }
  );

You want two functions as your arguments to then(). The first is your successCallback, the second your errorCallback.

As an alternative you may add an catch() to your promise chain. Which is easier to read and prevents errors like yours.

Upvotes: 1

Developer
Developer

Reputation: 6440

It should be either:

$http.get("myUrl")
    .then(function (response) {
        console.log(response);
    }
    ,function (error) {
        // Handle error here
    });

Or

$http.get("myUrl")
    .then(function (response) {
        console.log(response);
    })
    .catch (function(error) {
        // Handle error here
    });

Upvotes: 1

Related Questions