Join egghead, unlock knowledge.

Want more egghead? It's 45% off for a limited time only!

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock All Content for 45% Off

Already subscribed? Sign In

Save 45% for a limited time.

Get access to all courses and lessons on egghead today.

Autoplay

    Throw Errors with RxJS Observables

    André StaltzAndré Staltz

    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.

    rxjsRxJS
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    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 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.

    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.

    Discuss

    Discuss