如何才能不对错误 400 进行重试而仅通过 console.log 来记录错误?

问题描述 投票:0回答:1
@Injectable()
export class RetryInterceptor implements HttpInterceptor {
  private keycloakService = inject(KeycloakService);

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
    // console.log(this.keycloakService.getKeycloakInstance()?.tokenParsed);
    // console.log(request);

    return next.handle(request).pipe(
      retry({
        count: 3,
        delay: (error, retryCount) => {
          if (error.status === 503 || error.status === 504) {
            return timer(1000); // retry every 1 second for 503 and 504
          }
          return timer(retryCount * 1000); // Retry with increasing delay
        }
      }),
      catchError((error) => {
        if (error.status === 401) {
          return this.handleUnauthorized(request, next);
        }
        if (error.status === 503 || error.status === 504) {
        //   message that will redirect to the local UI URL if it comes back 503/504.
        }

        if (!noDisplayError) {

        }
        throw error;
      })
    );
  }
angular error-handling interceptor
1个回答
0
投票

您可以使用新的

retryWhen
替换为
delay and retry
,我们在出现 400 时抛出错误,然后抛出错误。我们使用
catchError
捕获并记录控制台消息,最后我们返回一个可观察值,以便流不会出错。

@Injectable()
export class RetryInterceptor implements HttpInterceptor {
  private keycloakService = inject(KeycloakService);

  intercept(
    request: HttpRequest<unknown>,
    next: HttpHandler
  ): Observable<HttpEvent<unknown>> {
    // console.log(this.keycloakService.getKeycloakInstance()?.tokenParsed);
    // console.log(request);

    return next.handle(request).pipe(
      retry({
        count: 3,
        delay: (error, retryCount) => {
          if (error.status === 503 || error.status === 504) {
            return timer(1000); // retry every 1 second for 503 and 504
          }
          if (error.status === 400) {
            return throwError(() => error); // just return an observable
          }
          return timer(retryCount * 1000); // Retry with increasing delay
        },
      }),
      catchError((error) => {
        if (error.status === 401) {
          return this.handleUnauthorized(request, next);
        }
        if (error.status === 503 || error.status === 504) {
          //   message that will redirect to the local UI URL if it comes back 503/504.
        }
        if (error.status === 400) {
          console.log('400 error occoured');
          return of({});
        }
        throw error;
      })
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.