27
/* 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?

1
  • 9
    tap is only to make side-effects and it doesn't modify the chain at all so to handle errors use catchError.
    – martin
    Oct 13, 2018 at 23:36

1 Answer 1

37

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.
    },
);
1
  • 6
    not exactly, tap has a second argument that will be called on error ;)
    – ggradnig
    May 18, 2020 at 14:24

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.