catch / catchError
signature: catchError(project : function): Observable
catchError(project : function): ObservableGracefully handle errors in an observable sequence.
⚠ Remember to return an observable from the catchError function!
Examples
( example tests )
Example 1: Catching error from observable
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+
import { throwError, of } from 'rxjs';
import { catchError } from 'rxjs/operators';
//emit error
const source = throwError('This is an error!');
//gracefully handle error, returning observable with error message
const example = source.pipe(catchError(val => of(`I caught: ${val}`)));
//output: 'I caught: This is an error'
const subscribe = example.subscribe(val => console.log(val));Example 2: Catching rejected promise
( StackBlitz | jsBin | jsFiddle )
Example 3: Catching errors comparison when using switchMap/mergeMap/concatMap/exhaustMap
( StackBlitz )
Additional Resources
catchError 📰 - Official docs
catchError - In Depth Dev Reference
Error handling operator: catch 🎥 💵 - André Staltz
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/catchError.ts
Last updated