0

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?

  1. Only 3 Re-attempts
  2. At an interval of 1 sec
  3. Only when the HTTP error code is 500

1 Answer 1

6

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...');
      })
    )
  )
);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.