⚠ Remember to return an observable from the catchError function!
( example tests )
Example 1: Catching error from observable
( StackBlitz | jsBin | jsFiddle )
// RxJS v6+import { throwError, of } from 'rxjs';import { catchError } from 'rxjs/operators';//emit errorconst source = throwError('This is an error!');//gracefully handle error, returning observable with error messageconst 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 )
// RxJS v6+import { timer, from, of } from 'rxjs';import { mergeMap, catchError } from 'rxjs/operators';//create promise that immediately rejectsconst myBadPromise = () =>new Promise((resolve, reject) => reject('Rejected!'));//emit single value after 1 secondconst source = timer(1000);//catch rejected promise, returning observable containing error messageconst example = source.pipe(mergeMap(_ =>from(myBadPromise()).pipe(catchError(error => of(`Bad Promise: ${error}`)))));//output: 'Bad Promise: Rejected'const subscribe = example.subscribe(val => console.log(val));
Example 3: Catching errors comparison when using switchMap/mergeMap/concatMap/exhaustMap
( StackBlitz )
// switchMap in example below can be replaced with mergeMap/concatMap/exhaustMap, the same behaviour appliesimport { throwError, fromEvent, of } from 'rxjs';import {catchError,tap,switchMap,mergeMap,concatMap,exhaustMap} from 'rxjs/operators';const fakeRequest$ = of().pipe(tap(_ => console.log('fakeRequest')),throwError);const iWillContinueListening$ = fromEvent(document.getElementById('continued'),'click').pipe(switchMap(_ => fakeRequest$.pipe(catchError(_ => of('keep on clicking!!!')))));const iWillStopListening$ = fromEvent(document.getElementById('stopped'),'click').pipe(switchMap(_ => fakeRequest$),catchError(_ => of('no more requests!!!')));iWillContinueListening$.subscribe(console.log);iWillStopListening$.subscribe(console.log);
catchError 📰 - Official docs
Error handling operator: catch
🎥 💵 - André Staltz
📁 Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/catchError.ts