Search⌘ K

Error Handling Operators

Let's explore RxJS error handling operators with the help of interactive examples.

Error Handling Operators in RxJS

All applications need error handling, and thankfully RxJS supplies a way of handling errors when working with Observables.

catchError() operator

The catchError() operator allows us to either throw an error if we encounter an error when using a source Observable or switch to a new Observable if there is an error.

Example

See the code given below.

C++
const { of } = require("rxjs");
const { map, catchError } = require("rxjs/operators");
of(1, 2, 3, 4, 5)
.pipe(
map((n) => {
// when n is 4 the error is thrown
if (n == 4) {
throw "four!";
}
return n;
}),
catchError((err) => of("I", "II", "III", "IV", "V"))
)
.subscribe((x) => console.log(x));

Looking at this example, we can see how the catchError() operator creates a new ...