0

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.

2
  • Under what circumstances will the server send you back invalid data? Commented Mar 21, 2015 at 2:17
  • When it's missing properties that my application needs. Commented Mar 21, 2015 at 2:53

2 Answers 2

1

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");
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.