Mark
Mark

Reputation: 4970

Angular promise - provide catch function

I am trying to come up with a generic service that would run my http requests and provides placeholders for success and error functions. Here is my code:

 var deferred = $q.defer();
 var response = $http({
  ..............
 });
 response.then(function (data) {
        deferred.resolve(data.data);
 });
 response.catch(function (data) {
        alert('Error');
 });

And in Controller:

service.executeHTTPCall('parameters').then(successHandler);

My question is how do I provide an error handler for an executeHTTPCall call?

Thanks

Upvotes: 1

Views: 459

Answers (1)

Benjamin Gruenbaum
Benjamin Gruenbaum

Reputation: 276596

Well, avoid the explicit construction and things fall into place:

// no deferred, just return
return $http({..... }).then(function(data){
    // handle successes
    return data.data;
}, function(err){ // handle failures here
     alert("ERrror!!!"); // logic here
     return $q.reject(err); // this is important, like a `catch and throw` 
                            // to signal we're still handling errors.
});

But, may I suggest http interceptors instead?

$httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  return {
    'response': function(response) {
       // do something on success
    }, 
    'responseError': function(rejection) {
       // do something on failure, see docs for more usage examples here
    };
});

That would mean you can avoid wrapping every $http promise manually and also play nicer with tests.

Upvotes: 4

Related Questions