Handling Errors

We can’t use the conventional try/catch mechanism in callbacks because it is synchronous. It would run before any asynchronous code, and wouldn’t be able to catch any errors.

With callbacks, this was solved by passing the error (if any) as a parameter to the callback function. That works, but it makes the code pretty fragile.

Let’s see how to catch errors inside Observables.

The onError Handler

Remember when we talked about the three methods we can call on an Observer, in First Contact with Observers? We’re familiar with onNext and onCompleted, but we haven’t yet used onError; it is the key to effectively handling errors in Observable sequences.

To see how it works, we’ll write a simple function to take an array of JSON ...

Get Reactive Programming with RxJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.