/* 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?
RxJS tap() operator is a utility operator that returns an observable output that is identical to the source observable but performs a side effect for every emission on the source observable.
RxJS catchError() operator is an error-handling operator used to handle and take care of catching errors on the source observable by returning a new observable or an error.
tap and do are same RxJS operators. RxJS tap and do are same operator. In Angular 6+, we need to use tap operator. tap /do performs side effects for every value emitted by source Observable and returns an Observable identical to the source Observable until there is no error.
With each call to catchError, we need to pass it a function which we will call the error handling function. The catchError operator takes as input an Observable that might error out, and starts emitting the values of the input Observable in its output Observable.
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(
() => {
// 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.
},
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With