Retry HTTP requests in angular 6

Amir Khademi

I use an interceptor to show error messages on display based on the HTTP response for every request.

intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const customReq = request.clone({
        //headers: request.headers.set('app-language', 'en')
    });
    return next
        .handle(customReq).pipe(
            tap((ev: HttpEvent<any>) => {
                if (ev instanceof HttpResponse) {
                    // processing request
                }
            }),
            catchError(response => {
                if (response instanceof HttpErrorResponse) {
                    switch (response.status) {
                        case 0:
                            // server API connection error show
                            break;
                        case 403:
                            // error Token Invalid and Redirect to logout
                            break;
                        case 401:
                            // error Token Invalid and Redirect to logout
                            break;
                        case 502:
                            // Bad gateway error
                            break;
                        case 500:
                            // internal server error
                            break;
                    }
                }
                // return next.handle(request);
                return observableThrowError(response);
            })
        );
}

In my project, the web server could be unavailable for a second in some case and reply a 500 error code. I don't want my web app to show an error message immediately after receiving an error and I want it to retry the request for a couple of times with a delay like one second.

I already tried rxjs retry :

...
.handle(customReq).pipe(retry(5),
...

it's not useful since it has no delay. based on this answer How to create an RXjs RetryWhen with delay and limit on tries

I tried retryWhen like:

.handle(customReq).pipe(
    tap((ev: HttpEvent<any>) => {
        if (ev instanceof HttpResponse) {
            console.log('###processing response', ev, this.location);
        }
    }),
    retryWhen(error => {
        return error
            .flatMap((error: any) => {
                if (error.status  == 400) {
                    return Observable.of(error.status).delay(1000);
                }
                if (error.status  == 0) {
                    return observableThrowError(error).delay(1000);
                }
                return observableThrowError(error);
            })
            .take(5)
            .concat(observableThrowError(error));
    }),

but it doesn't work as expected and it doens't go inside the if conditions.

m1ch4ls

There are several errors in your code:

  1. You are shadowing error variable - first it's an error stream and then it's an error object.
  2. Using observableThrowError with delay has no effect. Error will bypass every operator except those dealing with error.
  3. You are mixing "pipe(operator())" style operators and prototype style operators .operator().

I have suggested some changes:

.handle(customReq).pipe(
    tap((ev: HttpEvent<any>) => {
        if (ev instanceof HttpResponse) {
            console.log('###processing response', ev, this.location);
        }
    }),
    retryWhen(errors => errors
        .pipe(
            concatMap((error, count) => {
                if (count < 5 && (error.status == 400 || error.status == 0)) {
                    return Observable.of(error.status);
                }

                return observableThrowError(error);
            }),
            delay(1000)
        )
    ),

Main change is tracking error count through second argument of concatMap instead of using take opeator which is mainly useful for unsubscribing the observable and I think you want throw an error instead.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related