Angular - Catching error after all HTTP retry failed

后端 未结 4 1953
走了就别回头了
走了就别回头了 2021-01-07 10:06

I am using Angular Service to get data from my API. I implemented retry feature in case of fetching data fails. Now i need to handle the error when all the retr

4条回答
  •  抹茶落季
    2021-01-07 11:13

        return this.http.get(callURL,{
          params: new HttpParams()
            .set('page', page)
            .set('limit', limit)
        }).pipe(
          retryWhen(genericRetryStrategy({maxRetryAttempts: 10, scalingDuration: 1})),
          catchError(this.handleError)
        );
    

    Where genericRetryStrategy is from this retrywhen resource

    export const genericRetryStrategy = ({
      maxRetryAttempts = 3,
      scalingDuration = 1000,
      excludedStatusCodes = []
    }: {
      maxRetryAttempts?: number,
      scalingDuration?: number,
      excludedStatusCodes?: number[]
    } = {}) => (attempts: Observable) => {
      return attempts.pipe(
        mergeMap((error, i) => {
          const retryAttempt = i + 1;
          // if maximum number of retries have been met
          // or response is a status code we don't wish to retry, throw error
          if (
            retryAttempt > maxRetryAttempts ||
            excludedStatusCodes.find(e => e === error.status)
          ) {
            return throwError(error);
          }
          console.log(
            `Attempt ${retryAttempt}: retrying in ${retryAttempt *
              scalingDuration}ms`
          );
          // retry after 1s, 2s, etc...
          return timer(retryAttempt * scalingDuration);
        }),
        finalize(() => console.log('We are done!'))
      );
    };
    

    Stackblitz

提交回复
热议问题