Sequence onError Handler

Learn how to catch errors in a way that they are not caught before the asynchronous code.

We'll cover the following

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. This works, but makes the code fragile.

Let’s see how we can catch errors inside Observables.

The onError handler

Remember when we talked about the three methods we can call on an Observer, in the Creating Observables chapter? We’re familiar with the onNext and the onCompleted method, but we haven’t yet used the onError method. The onError method 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 strings and return an Observable that emits the objects parsed from those strings, using JSON.parse:

Get hands-on with 1200+ tech skills courses.