Aminadav Glickshtein
Aminadav Glickshtein

Reputation: 24590

In angular make $http go to catch if server response with {error:'ok'}

$http.get('/data.json')
.then(function(){console.log('ok'})
.catch(function(){console.log('no ok')})

The server response is:

200 OK
content-type: application/json

{error:'cannot get the data'}

I want that the response will go to the .catch not to .then.

I know that I can change the response header from the server, but I want to do it only on the client side.

In other Words:

How I make angular $http promise service, to think that 200 OK status, with "error" key in the response object, will go to catch instead of invoking the then function?

Upvotes: 1

Views: 701

Answers (3)

ohboy21
ohboy21

Reputation: 4319

As @yarons pointed out, you could use an interceptor. But, your decision was to always return 200, even in an error case, so why do you want to change this behaviour in your Front End now?

Your logic seems like:

Don't tell the front end to throw an error (maybe to not show in the dev console or let the user now), but handle it internally as an error.

For me, if you decide to go for this trick-behaviour, go all the way and don't hack something around. Just look in the then() for the error message.

So go in the then(), as you planned, and then catch your error there with an if clause:

$http.get('/data.json')
.then(function(response){
    if(response.data.error) {
       $scope.error_message = response.data.error;
       return;
    }
});

Upvotes: 1

Yaron Schwimmer
Yaron Schwimmer

Reputation: 5357

You can use an interceptor:

yourApp.factory('myInterceptor', ['$q', function($q) {
  return {
    response: function(response) {
      if (response.status === 200 && response.data.error) {
        return $q.reject(response);
      }
      else {
        return response;
      }
    }
  };
}]);

$httpProvider.interceptors.push('myInterceptor');

Upvotes: 1

$http.get('/data.json')
.then(function(res){
   if(res.error === 'cannot get the data'){
     return $q.reject(res)
   }
   return res;
)
.then(function(){console.log('ok'})
.catch(function(){
   console.log('no ok')
})

Just as others suggested, you can check for the conditions you want the request to be treated as a failure inside the .then block and reject using angular $q service reject() function

Upvotes: 1

Related Questions