catch / catchError

signature: catchError(project : function): Observable

Gracefully handle errors in an observable sequence.


⚠ Remember to return an observable from the catchError function!


Ultimate RxJS

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


📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/catchError.ts

Last updated