RavenHursT
RavenHursT

Reputation: 2344

Triggering error condition for AngularJS $http promises?

So I have a service defined as follows:

angular.module('services', ['ngResource'])
    .factory('Things', function ($rootScope, $http) {
    var basePath = 'rest/things/';
    return {
        getAll: function () {
            return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {});
        }
    };
});

Then, elsewhere, I'm consuming that service w/:

Things.getAll().success(function(things){
  //do something w/ things
})
.error(function(err){
  // Clearly, something went wrong w/ the request
});

What I'd like to do, is be able to "throw" the error condition if, for instance, there's a problem w/ the data at the service level. i.e.:

Data comes back as:

{
  status:500,
  message:'There was a problem w/ the data for this client'
}

And so then in the service there would be something like:

getAll: function () {
        return $http.post($rootScope.PAGES_URL + basePath + 'getAll/' + window.clientId, {})
  .throwError(function(data){
    return (data.status && data.status == 200);
  });
}

So when the throwError callback returns false, the error() promise would then be called instead of the success promise.

Does anyone have any ideas on how to accomplish this?

Thanks a bunch!

Upvotes: 2

Views: 3207

Answers (1)

Ian
Ian

Reputation: 50933

If you're sure that all requests will follow the convention where the data returned from a response includes a status code, then using an HTTP Interceptor makes sense. To do this, you can create a service and push it to the interceptor list for the $httpProvider:

.factory("myHttpInterceptor", function ($q) {
    return {
        response: function (response) {
            if (response.data.status && (response.data.status === 500)) {
                return $q.reject(response);
            }
            return response || $q.when(response);
        }
    };
});

You could replace the === 500 with something like >= 400 to handle all errors, not just a 500.

And inside your module's .config(), add this:

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

References:

Upvotes: 4

Related Questions