5

I'm currently chaining a bunch of http requests, however I am having trouble handling 404 errors before subscribing.

My code:

in template:

...
service.getData().subscribe(
    data => this.items = data,
    err => console.log(err),
    () => console.log("Get data complete")
)
...

in service:

...
getDataUsingUrl(url) {
    return http.get(url).map(res => res.json());
}

getData() {
    return getDataUsingUrl(urlWithData).flatMap(res => {
        return Observable.forkJoin(
            // make http request for each element in res
            res.map(
                e => getDataUsingUrl(anotherUrlWithData)
            )
        )
    }).map(res => {
        // 404s from previous forkJoin
        // How can I handle the 404 errors without subscribing?

        // I am looking to make more http requests from other sources in 
        // case of a 404, but I wouldn't need to make the extra requests 
        // for the elements of res with succcessful responses

        values = doStuff(res);

        return values;
    })
}
ray
  • 85
  • 1
  • 1
  • 5

2 Answers2

3

I think you could use the catch operator. The callback you provide when calling it will be called when an error will occur:

getData() {
  return getDataUsingUrl(urlWithData).flatMap(res => {
    return Observable.forkJoin(
        // make http request for each element in res
        res.map(
            e => getDataUsingUrl(anotherUrlWithData)
        )
    )
  }).map(res => {
    // 404s from previous forkJoin
    // How can I handle the 404 errors without subscribing?

    // I am looking to make more http requests from other sources in 
    // case of a 404, but I wouldn't need to make the extra requests 
    // for the elements of res with succcessful responses

    values = doStuff(res);

    return values;
  })
  .catch((res) => { // <-----------
    // Handle the error
  });
}
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360
  • Thank you! catch solved my problem, but to handle each error individually during the forkJoin call, I needed to catch the errors in the getDatausingUrl method. – ray Feb 25 '16 at 02:13
  • @Thierry Templier I have somewhat of a similar problem. One of the three queries that run in my forkjoin returns a 404. I catch the error, but it prevents me from getting the results of the two other queries. It's like the whole process stops. Any ideas on what's causing this behaviour ? Thanks ! – Standaa - Remember Monica Mar 22 '17 at 18:08
  • Ok, thank you, solved using [this S.O question](http://stackoverflow.com/questions/38048860/angular2-rxjs-observable-forkjoin). – Standaa - Remember Monica Mar 23 '17 at 12:54
3

This was answered pretty well here: https://stackoverflow.com/a/38061516/628418

In short you put a catch on each observable before you hand them to forkJoin.

Sámal Rasmussen
  • 2,887
  • 35
  • 36