Learn RxJS
Search…
catch / catchError

signature: catchError(project : function): Observable

Gracefully handle errors in an observable sequence.

⚠ Remember to return an observable from the catchError function!

Examples

Example 1: Catching error from observable
1
// RxJS v6+
2
import { throwError, of } from 'rxjs';
3
import { catchError } from 'rxjs/operators';
4
//emit error
5
const source = throwError('This is an error!');
6
//gracefully handle error, returning observable with error message
7
const example = source.pipe(catchError(val => of(`I caught: ${val}`)));
8
//output: 'I caught: This is an error'
9
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 2: Catching rejected promise
1
// RxJS v6+
2
import { timer, from, of } from 'rxjs';
3
import { mergeMap, catchError } from 'rxjs/operators';
4
5
//create promise that immediately rejects
6
const myBadPromise = () =>
7
new Promise((resolve, reject) => reject('Rejected!'));
8
//emit single value after 1 second
9
const source = timer(1000);
10
//catch rejected promise, returning observable containing error message
11
const example = source.pipe(
12
mergeMap(_ =>
13
from(myBadPromise()).pipe(catchError(error => of(`Bad Promise: ${error}`)))
14
)
15
);
16
//output: 'Bad Promise: Rejected'
17
const subscribe = example.subscribe(val => console.log(val));
Copied!
Example 3: Catching errors comparison when using switchMap/mergeMap/concatMap/exhaustMap
1
// switchMap in example below can be replaced with mergeMap/concatMap/exhaustMap, the same behaviour applies
2
import { throwError, fromEvent, of } from 'rxjs';
3
import {
4
catchError,
5
tap,
6
switchMap,
7
mergeMap,
8
concatMap,
9
exhaustMap
10
} from 'rxjs/operators';
11
12
const fakeRequest$ = of().pipe(
13
tap(_ => console.log('fakeRequest')),
14
throwError
15
);
16
17
const iWillContinueListening$ = fromEvent(
18
document.getElementById('continued'),
19
'click'
20
).pipe(
21
switchMap(_ => fakeRequest$.pipe(catchError(_ => of('keep on clicking!!!'))))
22
);
23
24
const iWillStopListening$ = fromEvent(
25
document.getElementById('stopped'),
26
'click'
27
).pipe(
28
switchMap(_ => fakeRequest$),
29
catchError(_ => of('no more requests!!!'))
30
);
31
32
iWillContinueListening$.subscribe(console.log);
33
iWillStopListening$.subscribe(console.log);
Copied!

Additional Resources

Last modified 6mo ago