glcohen glcohen - 25 days ago 7
AngularJS Question

$q.all -- resolving http request error on some request, but not others

I have some code that looks like this

angular.forEach(config.tvshows.shows, function(show) {
promises.push($http.get('http://epguides.frecar.no/show/' + show.replace(/\s|\./g, '') + '/next/'));
});

return $q.all(promises).then(function(response) {
for (var i = 0; i < response.length; i++) {
service.shows.push(response[i]);
}
});
};


The idea is that I have a list (promises) comprised of http requests. Most are successful, but some may fail. I cannot simply remove the failing request, because they may succeed sometimes, and fail other times.

However, if one of the responses fails, I do not get any responses pushed to 'service.shows'. Is there a way to handle a 404, or any error response on a http request so that for the working request the code runs properly?

Answer

You can add your custom handler to failed http requests like so:

angular.forEach(config.tvshows.shows, function(show) {
      promises.push($http.get('http://epg\./g, ') + '/next/').catch(function() {
    // return whatever is needed here
}));

  });

In this way, if a response fails, you can return your canned response and $q.all chain will not stop. If the response doesn't fail, you'll get the response sent by server.