angularrequestangular-httpclientangular-http-interceptors

Angular request duplicate if error is throw


I have a weird behavior with my requests. If the request throw an error, I automatically get a second one launched

enter image description here

Here is an example of my request :

this.http.post(environment['url'] + '/ws/verifier/documents/list', {}, {headers}).pipe(
    tap((data: any) => {
        ....
    }),
    finalize(() => {
        ....
    }),
    catchError((err: any) => {
        console.debug(err);
        this.notify.handleErrors(err);
        return of(false);
    })
).subscribe();

How can I do to avoid this duplicated request if an error is thrown ?

Thanks

EDIT : I have this interceptor. Used to refresh token if error 401 is thrown. But if it's another error, the request is resend. Is there any solutions to avoid that ?

intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    return next.handle(request).pipe(
        catchError((err: any) => {
            if (err.status === 401) {
                return this.handle401Error(request, next);
            }
            return next.handle(request);
        })
    );
}

Solution

  • The problem is probably that you are calling next.handle(request) twice. Since calling that function passes request to the next interceptor in chain you are executing chain twice hence request is duplicated. From docs:

    The next object represents the next interceptor in the chain of interceptors. The final next in the chain is the HttpClient backend handler that sends the request to the server and receives the server's response.

    What you might want is this:

    intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
        return next.handle(request).pipe(
            catchError((err: any) => {
                if (err.status === 401) {
                    return this.handle401Error(request, next);
                }
                return throwError((err) => err); // or handle error in some other way
            })
        );
    }
    

    Also, since you are passing next to handle401Error function, take care not to call next.handle() in it because you might meet the same problem you are now having.