Which RxJS operator to choose to handle HTTP errors: tap or catchError?
Asked Answered
V

1

29
/* 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', [])
  );
}

now using tap to handle errors

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
    })
  );
}

Why should I choose one approach instead of the other? Will handling HTTP errors with tap() keep my app' running in case they occur?

Vanesavanessa answered 13/10, 2018 at 22:45 Comment(1)
tap is only to make side-effects and it doesn't modify the chain at all so to handle errors use catchError.Seleta
S
40

tap is to cause side effects.

catchError is to catch errors in a stream and try to handle them.

Therefore if you want to handle errors of http requests use catchError.

http.get('https://test.com/').pipe(
    tap({
        next: () => {
            // 200, awesome!, no errors will trigger it.
        },
        error: () => {
            // 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.
    },
);
Silvery answered 16/5, 2020 at 11:44 Comment(1)
not exactly, tap has a second argument that will be called on error ;)Pignus

© 2022 - 2024 — McMap. All rights reserved.