Throw Errors with RxJS Observables

André Staltz
InstructorAndré Staltz

Share this video with your friends

Send Tweet
Published 6 years ago
Updated a year ago

Whenever we are writing code, we need to remember that things may go wrong. If an error happens in a function, that error will be thrown. Errors can also happen in Observables.

In this lesson we will see what the API is for throwing and catching Errors with Observables.

[00:00] Whenever we are writing code, we need to remember that things may go wrong. If an error happens inside a function, like here, that error will be thrown, and it will start bubbling up the stack of function calls. That's why it's generally a good idea to wrap function calls with a try/catch block to handle the error, and then other code can continue running.

[00:19] So what about with observables? Of course, things may go wrong inside observable code, and we need to be able to handle errors, so how do we throw errors from an observable? The answer is rather simple: we use observer.error. And this allows us to sort of deliver an error. The API here is similar to; essentially, instead of delivering a value, we are delivering an error. And then to catch those errors, we need to modify the code here for the consumers that subscribe.

[00:50] If we would name this first function, I would give it the name 'next value handler'. And then 'subscribe' also accepts another function, which is the error handler. So this is similar to the catch block, and here we can do something like this: something went wrong, which is this error.

[01:14] So if you are using the observable.create API, it's generally a good idea to wrap this code in a try/catch block, and then inside the catch, you can send this error to the observer, like such. And that is generally the strategy for handling errors in observables.

Voi Admin
Voi Admin
~ 6 years ago

The final step wraps the setTimeout call in a try/catch block, however as I understand, if an error is thrown within the setTimeout, it will not be caught.

André Staltz
André Staltzinstructor
~ 6 years ago

Correct. The focus of this lesson was to demonstrate that errors can be caught inside Observable.create, and that you can pass those errors to the Observer. How those errors are actually caught is a different topic, and ideally I would place a try catch inside setTimeout too, and then pass those errors to the Observer as well.