One of the things I found most annoying about learning RxJS was the error handling. There were examples of "standard" error handling methods, and they made essentially zero sense to me. I couldn't understand how to use them for what I actually wanted.
Sure, a standard error handler that logs out to the console is nice, but error handling usually needs to be customized for the needs of a specific place in code.
One of the things I just couldn't figure out was how to trap an error and then take a specific action if it's a specific error (like maybe the HTTP endpoint returned a 403 error and you want to just display a message about invalid username/password)
It wasn't until I finally started to really research error handling in RxJS that I learned how to really do this.
Ultimately, it wasn't learning how to do the specific task that I needed, what I needed was to learn how things actually worked. So let's do just a little of that today.
Error handling with RxJS mainly happens with the catchError operator.
This operator allows you to do one of only two things:
Throw an error
Return a new observable
Mostly we see people doing the first thing. They log to the console, then throw a new error. This is called "Catch and Rethrow".
It's the second feature that allows you to do TRULY interesting things with error handling. Because the observable that you decide to return now replaces whatever was happening before, and so you can use that as a signal to the subscriber that a specific thing happened, and so take a specific action.
Here's an example subscriber:
And now to support this we can easily write a catchError for this:
See how I returned an object that has the authenticated property set to false? That's the signal to the subscriber that login failed. I do that when the error thrown has the error status of 403.
Of course, I could have used any property. I chose a boolean property of "authenticated" but I could have used anything to communicate that this is a special case I want to handle.
This capability in catchError is the core understanding you need to handle errors in RxJS and use them to do whatever it is your application needs.
It's time for you to practice. Try out this stackblitz exercise. It should take you less than a minute. If you get stuck (but ONLY if you get stuck) check out the solution.
Enjoy this discussion? Sign up for our newsletter here.
Posted on by: