哪个rxjs运算符选择处理http错误:tap()或catchError()?

问题描述 投票:5回答:1
/* 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', [])
  );
}

现在正在使用水龙头处理错误

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错误是否可以使我的应用正常运行?

rxjs angular-httpclient
1个回答
0
投票

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 EMPTY; // or any other stream like of('') etc.
            }

            // other errors we don't know how to handle and throw them further.
            return throwError(error);
        },
    ),
);
© www.soinside.com 2019 - 2024. All rights reserved.