function stable operator
Catches errors on the observable to be handled by returning a new observable or throwing an error.
catchError(selector: (err: any, caught: Observable<T>) => O): OperatorFunction<T, T | ObservedValueOf<O>> selector | (err: any, caught: Observable<T>) => O |
OperatorFunction<T, T | ObservedValueOf<O>>
This operator handles errors, but forwards along all other events to the resulting observable. If the source observable terminates with an error, it will map that error to a new observable, subscribe to it, and forward all of its events to the resulting observable.
Continue with a different Observable when there's an error
import { of, map, catchError } from 'rxjs';
of(1, 2, 3, 4, 5)
.pipe(
map(n => {
if (n === 4) {
throw 'four!';
}
return n;
}),
catchError(err => of('I', 'II', 'III', 'IV', 'V'))
)
.subscribe(x => console.log(x));
// 1, 2, 3, I, II, III, IV, V Retry the caught source Observable again in case of error, similar to retry() operator
import { of, map, catchError, take } from 'rxjs';
of(1, 2, 3, 4, 5)
.pipe(
map(n => {
if (n === 4) {
throw 'four!';
}
return n;
}),
catchError((err, caught) => caught),
take(30)
)
.subscribe(x => console.log(x));
// 1, 2, 3, 1, 2, 3, ... Throw a new error when the source Observable throws an error
import { of, map, catchError } from 'rxjs';
of(1, 2, 3, 4, 5)
.pipe(
map(n => {
if (n === 4) {
throw 'four!';
}
return n;
}),
catchError(err => {
throw 'error in source. Details: ' + err;
})
)
.subscribe({
next: x => console.log(x),
error: err => console.log(err)
});
// 1, 2, 3, error in source. Details: four!
© 2015–2022 Google, Inc., Netflix, Inc., Microsoft Corp. and contributors.
Code licensed under an Apache-2.0 License. Documentation licensed under CC BY 4.0.
https://rxjs.dev/api/operators/catchError