调用API角度时如何忽略http响应错误

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

如何忽略HTTP响应错误并返回响应,因为我在使用角度HTTP客户端时从API调用,这是我调用API的代码

Api处理程序:

get<T>(url:string):Observable<T> {

    return this.http.get<T>(url, this.getRequestHeaders()).pipe<T>(
      catchError(error => {
        return this.handleError(error, () => this.get(url));
      }));
  }

处理错误:

protected handleError(error, continuation: () => Observable<any>) {
    if (error.status == 401) {
        if (this.isRefreshingLogin) {
            return this.pauseTask(continuation);
        }
        this.isRefreshingLogin = true;

        return this.authService.refreshLogin().pipe(
            mergeMap(data => {
                this.isRefreshingLogin = false;
                this.resumeTasks(true);

            return continuation();
        }),
        catchError(refreshLoginError => {
          this.isRefreshingLogin = false;
          this.resumeTasks(false);

          if (refreshLoginError.status == 401 || (refreshLoginError.url && refreshLoginError.url.toLowerCase().includes(this.loginUrl.toLowerCase()))) {
            this.authService.reLogin();
            return throwError('session expired');
          }
          else {
            return throwError(refreshLoginError || 'server error');
          }
        }));
    }
angular
1个回答
1
投票

如果你想在错误代码404和400上继续正常流程,你只需要在遇到这些代码时返回一个假的Observable,如下所示:

import { of } from 'rxjs/observable/of';
...
protected handleError(error, continuation: () => Observable<any>) {
    if (error.status == 404 || error.status == 400) {
        return of(false);
    }
    ...
}
© www.soinside.com 2019 - 2024. All rights reserved.