【问题标题】:Which RxJS operator to choose to handle HTTP errors: tap or catchError?选择哪个 RxJS 操作符来处理 HTTP 错误:tap 还是 catchError?
【发布时间】:2018-10-13 22:45:08
【问题描述】:
/* error handler that will be used below in pipe with catchError() 
 * when resource fetched with HttpClient get() */

private _handleError<T> (operation: string, result?:T) {
     return( error: any): Observable<T> => {
          console.error( operation + ' ' + error.message );
          // or something else I want to do
          return of(result as T); // lets me return innocuous results
     }
}

getObjects() {
  return this.http.get<any[]>(this.myUrl).pipe(
    catchError(this._handleError('my error', [])
  );
}

现在使用tap 处理错误

getObjects() {
  return this.http.get<any[]>(this.myUrl).pipe(
    tap( objects => {
      // whatever action like logging a message for instance
    }, err => {
      console.error(err);
      // whatever else I want to do
    })
  );
}

为什么我应该选择一种方法而不是另一种?使用tap() 处理 HTTP 错误是否会在发生时让我的应用继续运行?

【问题讨论】:

  • tap 只是为了产生副作用,它根本不修改链,所以处理错误使用catchError

标签: rxjs angular-httpclient


【解决方案1】:

tap会引起副作用。

catchError 是捕捉流中的错误并尝试处理它们。

因此,如果您想处理http 请求的错误,请使用catchError

http.get('https://test.com/').pipe(
    tap(
        () => {
            // 200, awesome!, no errors will trigger it.
        },
        () => {
            // error is here, but we can only call side things.
        },
    ),
    catchError(
        (error: HttpErrorResponse): Observable<any> => {
            // we expect 404, it's not a failure for us.
            if (error.status === 404) {
                return of(null); // or any other stream like of('') etc.
            }

            // other errors we don't know how to handle and throw them further.
            return throwError(error);
        },
    ),
).subscribe(
    response => {
        // 200 triggers it with proper response.
        // 404 triggers it with null. `tap` can't make 404 valid again.
    },
    error => {
        // any error except 404 will be here.
    },
);

【讨论】:

  • 不完全是,tap 有第二个参数,将在错误时调用;)
  • 很棒的例子。谢谢。
猜你喜欢
  • 2019-09-07
  • 1970-01-01
  • 2020-10-07
  • 2021-02-12
  • 1970-01-01
  • 2011-06-11
  • 2020-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多