Handle errors with catchError

v.7

v.18

Fabio Biondi
Google Developer Expert
Microsoft MVP
# HttpClient and Signal
Let’s start with a simple example where we make a call to the server to retrieve a list of users and display them in the template:
We can also use toSignal
or async
pipe as we saw in previous lessons
# Errors
But what happens if there are errors?
If the endpoint returns an error (and we simulate it by entering a wrong endpoint) we will encounter an unhandled error that will not be handled in any way.
We will not have any notification and we will not be able to handle it in any way:
# Handling Errors with an Observer
Let's explore two ways to handle errors in the given script: one with an observer (using next, error, and complete methods) and another using RxJS's catchError operator.
Let's start with the first one, using observer.
In this approach, you manually subscribe to the observable and pass an observer object with methods to handle next
, error
, and complete
scenarios.
This approach allows for error management. For example, we can set a signal to indicate that an error has occurred and then display an appropriate message in the template:
next
: This is triggered when the HTTP request successfully returns user data. You handle the emitted value (users
) here.
error
: This is triggered if the HTTP request fails (e.g., network issues, server errors), allowing you to handle the error case.
complete
: This is called when the observable completes its emission, meaning no more values will be emitted.
# Handling Errors with catchError
Operator