Search code examples
angularrefresh

catchError not working in angular refresh token


I tried to show error message on 401 if refresh token call is failed but unable to get in catchError function. I have searched it but unable to find a useful solution. Before mark this as duplicate please first check if the solution works or not.

  private handle401Error(request: HttpRequest<any>, next: HttpHandler) {
    if (!this.isRefreshing) {
      this.isRefreshing = true;
      this.refreshTokenSubject.next(null);

      const token = this.authService.getRefreshToken();
      if (token)
        return this.authService.refreshToken().pipe(
          switchMap((res: any) => {
            this.isRefreshing = false;
            localStorage.setItem("access_token", res.data.access_token.token);
            localStorage.setItem("refresh_token", res.data.refresh_token.token);
            this.refreshTokenSubject.next(res.data.access_token.token);
            return next.handle(this.addTokenHeader(request, res.data.access_token.token));
          }),
          catchError((err) => {
            this.isRefreshing = false;
            
            this.authService.logout();
            return throwError(err);
          })
        );
    }

    return this.refreshTokenSubject.pipe(
      filter(token => token !== null),
      take(1),
      switchMap((token) => next.handle(this.addTokenHeader(request, token))),
    );
  }

switchMap works when i get a success it works fine but when i get error its not calling catchError function.


Solution

  • I have fixed this issue. Now i am getting error message on refresh token as well. CatchError works now here is the code

      if (refreshToken) {
        return this.authService.refreshToken().pipe(
          tap((accessToken) => {
            this.isRefreshing = false;
            localStorage.setItem("access_token", accessToken.data.access_token.token);
            localStorage.setItem("refresh_token", accessToken.data.refresh_token.token);
          }),
          switchMap((accessToken) => {
            this.refreshTokenSubject.next(accessToken.data.access_token.token);
            return next.handle(this.addTokenHeader(request, accessToken.data.access_token.token));
          }),
          catchError((err) => {
            this.isRefreshing = false;
            localStorage.clear();
            this.router.navigate(["/"]);
            return throwError('Unauthorized');
          })
        );
      } else {
        this.isRefreshing = false;
        localStorage.clear();
        this.router.navigate(["/"]);
        return throwError('Unauthorized');
      }