Reputation: 6546
How can i retry after catch ?
I want to retry my observable after catch method automatically without calling another subscribe. How can i do that ?
I have something like this for now:
intercept(observable: Observable<Response>): Observable<Response> {
return observable.catch((err, source) => {
return this.refreshToken()
.flatMap(res => {
if (res.status === 200) {
return observable;
}
return Observable.throw(new Error('Can\'t refresh the token'));
});
});
}
So when i have my observable and call subscribe
on it it will catch error ->
refresh token ->
and then return observable where i have to call another subscribe. I dont want to do that. how can i make it work with that subscribe before ?
The call example will looke something like this:
let request = this.http.request(url);
intercept(request).subscribe(res => { //do something });
Upvotes: 1
Views: 2973
Reputation: 18665
There are a couple of operators which can be used in conjunction with catch to handle retrial/repetition. They are useful operators, they allow you to conditionally resubscribe to observables which have terminated. From the official documentation for retryWhen
:
Repeats the source observable sequence on error when the notifier emits a next value. If the source observable errors and the notifier completes, it will complete the source sequence.
Additional info here :
You can find some examples here from previous questions:
From the second SO question :
src.retryWhen(function (errors) {
// retry for some errors, end the stream with an error for others
return errors.do(function (e) {
if (!canRetry(e)) {
throw e;
}
});
});
Upvotes: 3