1

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?

glcohen
  • 193
  • 1
  • 1
  • 11

1 Answers1

4

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.

Max Koretskyi
  • 101,079
  • 60
  • 333
  • 488
  • Are you sure this works? I get the following error: `angular.js:13920 TypeError: promises.push(...).catch is not a function` – glcohen Nov 14 '16 at 07:51
  • 1
    you need to add `catch` to `get` function, not `push` - like this `$http.get().catch` – Max Koretskyi Nov 14 '16 at 07:55
  • Thanks, that worked. I now am able to log an error, but it seems the 404 http request still gets pushed to 'promises'. Is there a way around that? – glcohen Nov 14 '16 at 07:59
  • what do you return from `catch`? what do you mean by _the 404 http request still gets pushed to 'promises'_? – Max Koretskyi Nov 14 '16 at 08:02
  • Edit: I've handled filtering out the error messages. In catch I just log the message `console.log("Error with show: " + show);` But, in my JS console I still see the 404 message in red -- can that be muted? – glcohen Nov 14 '16 at 08:11
  • I think you should take a look [at this](http://stackoverflow.com/questions/14337351/can-i-prevent-the-chrome-developer-tools-console-from-logging-image-404-errors/14427545#14427545) – Max Koretskyi Nov 14 '16 at 08:18
  • Thank you, I appreciate it! – glcohen Nov 14 '16 at 08:20