Home > Net >  RxJs use catchError like retry
RxJs use catchError like retry

Time:04-01

I'm looking for a possibility to call a catchError repeatingly / recursive for a http call. First I just used retry(x) but now I need to modify the request in case of an error.

Right now the catchError get called only once (for sure). How to modify it?

export class HttpErrorInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let attempts = 0;

        return next.handle(request).pipe(
            catchError(e => {
                attempts  ;
                if (attempts < 5) { return next.handle(request.clone({ ...{} })); }
                throw e;
            })
        );
    }
}

CodePudding user response:

so if you just need to modify the first time, just put the retry on your modified observable inside the catchError:

export class HttpErrorInterceptor implements HttpInterceptor {
    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            catchError(e => {
                return next.handle(request.clone({ ...{} })).pipe(retry(4));
            })
        );
    }
}

if you need to modify every time, a recursive error handler will do it:

export class HttpErrorInterceptor implements HttpInterceptor {

    private handleError(request: HttpRequest<any>, next: HttpHandler, error, attempts: number) {
      return next.handle(request.clone({ ...{} })).pipe(
        catchError(e => (attempts < 5) ? this.handleError(request, next, e, attempts   1) : throwError(e))
      )
    }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            catchError(e => this.handleError(request, next, e, request, 1))
        );
    }
}
  • Related