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;
})
}
The forkJoin will subscribe to the passed observables, by making the HTTP GET requests. If any input observable errors at some point, forkJoin will find the error as well and all other observables will be immediately unsubscribed.
ForkJoin method signature has changed This is now deprecated and you must pass an array of observables to forkJoin operator.
concat() which will handle each observable in sequence.
forkJoin will wait for all passed observables to emit and complete and then it will emit an array or an object with last values from corresponding observables.
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
});
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With