This lesson is for PRO members.

Unlock this lesson NOW!
Already subscribed? sign in

Observables can throw errors

1:39 RxJS lesson by

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, and in this lesson we will see what is the API for throwing and catching them.

Get the Code Now
click to level up

egghead.io comment guidelines

Avatar
egghead.io

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, and in this lesson we will see what is the API for throwing and catching them.

Avatar
Admin

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.

Avatar
Andre

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.

In reply to Admin

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.

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 observer.next; 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.

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.

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.

HEY, QUICK QUESTION!
Joel's Head
Why are we asking?