Angular拦截器正在改变错误的HTTP响应的pipleline

问题描述 投票:0回答:1

我被要求修改现有的有角度的http拦截器,特别是添加逻辑以在对API的请求失败时在开发人员控制台中显示错误。

[阅读了一些有关它的文章之后,我读到在响应中结合使用pipetap可以使用catchError来显示它。

该部分正在工作,但似乎管道受到了影响,因为即使我在Observable函数上返回了错误的catchError,该值也没有返回到该管道的接收端(即当在API调用上使用订阅时)

这是我拥有的拦截器的相关代码。

我在做什么,这正在影响管道?为什么即使我返回错误,现有代码也没有收到错误。

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {
    if (!this.isRefreshingToken) {
      // not relevant logic
    }

    const reqCopy = this.addHeaderToRequest(req);

    // continue the request flow and tap into the response
    return next.handle(reqCopy).pipe(
      tap(evt => {
        if (evt instanceof HttpResponse) {
          if (evt.status === 500) {
            console.log(">>", evt.body);
          }
        }
      }),
      catchError((err: any) => {
        /* in case a special logic is neeeded for HttpErrorResponse
        if(err instanceof HttpErrorResponse) {

        }
        */
       console.error(err) ;

       if(!!err.error) {
        console.error(JSON.stringify(err.error));
       }

        // return an observable of the error as required by the pipeline
        return of(err);
      })
    );
}

这是用于正常工作的API的调用代码,这意味着//失败的逻辑是在调用后端时收到错误时执行的,但是现在不执行该逻辑,因此许多其他api调用。

this.service.login(this.model).subscribe(
  // login successful
  () => {
      //not relevant code
  },
  // login failed
  error => {
    this.ssoService.init();
    console.log("Login error: ", error);
    switch (error.originalError.status) {
      case 307: 
        // need password change
        break;
      case 400:
        this.notificationService.showError(
          NotificationMessages.LoginUserOrPasswordIncorrect
        );
        break;
      case 423:
        this.error = NotificationMessages.LoginAccountLocked;
        break;
      case 404:
        this.notificationService.showError(
          NotificationMessages.LoginUserOrPasswordIncorrect
        );
        break;
      default:
        break;
    }
angular angular-http-interceptors
1个回答
0
投票

在拦截函数中,您正在返回next.handle(reqCopy).pipe(,它不是Observable<HttpEvent<any>>的类型。

您需要按照以下方式处理。

intercept(
req: HttpRequest<any>,
next: HttpHandler
): Observable<HttpEvent<any>> {

    const reqCopy = req;

    // continue the request flow and tap into the response
    const event = next.handle(reqCopy);
    event.pipe(
      tap(evt => {
        // ... your code
      }),
      catchError((err: any) => {
          //....... your code
        return of(err);
      })
    );

    return event;
}

这里是演示-https://stackblitz.com/edit/angular-interceptors-8aygw4

希望这会有所帮助。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.