rxjs - 选择哪个 RxJS 操作符来处理 HTTP 错误 : tap or catchError?

标签 rxjs angular-httpclient

/* 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是在流中捕获错误并尝试处理它们。

因此,如果您想处理 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.
    },
);

关于rxjs - 选择哪个 RxJS 操作符来处理 HTTP 错误 : tap or catchError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52797992/

相关文章:

Angular ,HttpClient;属性 '.shareReplay' 在类型 'Observable' 上不存在

javascript - RxJS:缓存几个没有可变性和副作用的 XHR 调用

error-handling - Angular httpClient retryWhen block 处理错误

angular - 如何使用 BehaviourSubjects 在 Angular 组件之间共享 API 调用的数据?

angular - HttpRequest 和 reportProgress 不起作用或弄乱了我的请求

angular - 使用 HttpParams 和 FromObject 有条件地添加参数并使用变量作为键名

Angular 4 : Module not found error regarding RxJs

angular - observer.error()之后需要调用observer.complete()?

Angular 6 : Cannot find a differ supporting object '[object Object]' of type 'object' . NgFor 只支持绑定(bind)到 Iterables 之类的 Arrays