角度拦截器,处理HTTP错误并重试

时间:2020-04-11 11:48:51

标签: typescript error-handling rxjs interceptor angular9

我有一个基本的JWT系统,还有一个Interceptor,用于检查请求是否由于未经授权而失败。

import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {AuthService} from '../services/auth.service';
import {catchError, retryWhen} from 'rxjs/operators';

@Injectable()
export class AuthenticationErrorInterceptor implements HttpInterceptor {

  private readonly _authService: AuthService;

  constructor(authService: AuthService) {
    this._authService = authService;
  }

  public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    const authReq = req.clone({headers: req.headers});
    return next.handle(authReq)
      .pipe(
        catchError((err) => this._handleAuthError(err)),
        retry(3)
      );
  }

  private _handleAuthError(error: HttpErrorResponse): Observable<any> {
    if (error.status === 401 || error.status === 403) {
      return this._authService.authenticate();
    }

    return throwError(error);
  }
}

如果请求确实失败,那么我想在致电this._authService.authenticate();之后重新发送请求。由于错误处理的原因,它将强制进行重新认证,但是它将不会重新调用导致应用程序失败的请求,直到我刷新浏览器为止。

如何让我的警卫再次尝试该请求?

我也尝试过使用retryWhen,但得到的结果相同/相似。

1 个答案:

答案 0 :(得分:1)

重新认证会话后,请在HTTP处理程序上调用.next。理想情况下,您应该从您的authenticate方法中返回一个身份验证令牌,然后可以将其附加到请求auth标头中。

import {Injectable} from '@angular/core';
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
import {AuthService} from '../services/auth.service';
import {catchError, retryWhen} from 'rxjs/operators';

@Injectable()
export class AuthenticationErrorInterceptor implements HttpInterceptor {

  private readonly _authService: AuthService;

  constructor(authService: AuthService) {
    this._authService = authService;
  }

  public intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
      return next.handle(req)
            .pipe(
                catchError((error: HttpErrorResponse) => {
                  if (error.status === 401 || error.status === 403) {
                    return this._authService.authenticate()
                      .pipe(
                        mergeMap((token) => next.handle(req.clone({
                                    headers: req.headers.set(AUTH_TOKEN_NAME_HERE, token)
                                })))
                      );
                  }

                    return throwError(error);
                })
            );
  }
}