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