I am trying to add a simple HTTP re-attempt to my API calls as
this.http.post(url, {payload})
.pipe(retry(3)).sub.....
How do I add the following cases?
- Only 3 Re-attempts
- At an interval of 1 sec
- Only when the HTTP error code is 500
You can make use of retryWhen from RxJS to retry any requests. below is a code snippet that tries for 3 times before throwing the error:
private handleRetry<T>(source: Observable<T>): Observable<T> {
return source.pipe(retryWhen(e => e.pipe(scan((errorCount, error) => {
if (errorCount >= 3) {
throw error;
}
return errorCount + 1;
}, 0),
delay(1000)
)));
}
in the component call you can make use of handleRetry :
this.http.post(url, {payload})
.pipe(this.handleRetry).sub.....
You can also tap into the error to decide if you have to retry based on the status code:
Ex:
server.getData().pipe(
retryWhen(errors =>
errors.pipe(
delay(1000),
tap(errorStatus => {
if (!errorStatus.startsWith('5')) {
throw errorStatus;
}
console.log('Retrying...');
})
)
)
);