Error Handling in RxJs

A few days ago, we saw that we could be notified of any error when subscribing using a specific callback function or that we could receive the same information using the tap operator.

There is another option available using a specialized operator called catchError and illustrated below under its deprecated name catch:

How does catchError help? As we can see in the marble diagram, it can return a different Observable when an error happens. This means that the subscriber would have no idea that something wrong happened as we are able to switch to a backup solution (perhaps some cached data or a different API endpoint).

This is especially important when you know that if an Observable throws an error, it will never emit another value in the future. This makes catchError an excellent option to recover or at least attempt to recover from an error in the browser. We will cover other options (such as operators that retry an Observable) in the subsequent editions of the newsletter.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.