user56512
user56512

Reputation:

How to fail a successful Angular JS $http.get() promise

How do I reject or fail a successful $http.get() promise? When I receive the data, I run a validator against it and if the data doesn't have required properties I want to reject the request. I know I can do after the promise is resolved, but it seems like a good idea to intercept errors as soon as possible. I'm familiar with the benefits of $q, but really want to continue using $http.

Upvotes: 0

Views: 270

Answers (2)

New Dev
New Dev

Reputation: 49610

You can reject any promise by returning $q.reject("reason") to the next chained .then.

Same with $http, which returns a promise - this could be as follows:

return $http.get("data.json").then(function(response){
  if (response.data === "something I don't like") {
    return $q.reject("bad data");
  }
  return response.data;
}

This could simply be done within a service, which pre-handles the response with the .then as specified above, and returns some data - or a rejection.

If you want to do this at an app-level, you could use $http interceptors - this is just a service that provides functions to handle $http requests and responses, and allows you to intercept a response and return either a response - same or modified - or a promise of the response, including a rejection.

.factory("fooInterceptor", function($q){
  return {
    response: function(response){
      if (response.data === "something I don't like") {
        return $q.reject("bad data");
      }
      return response;
    }
  }
});

Same idea as above - except, at a different level.

Note, that to register an interceptor, you need to do this within a .config:

$httpProvider.interceptors.push("fooInterceptor");

Upvotes: 1

Alex Soroka
Alex Soroka

Reputation: 810

You can use AngularJS interceptors. But you still need to use $q in them because $http uses $q.

Here is a useful article about interceptors.

Upvotes: 0

Related Questions