Error handling is an essential part of RxJs, as we will need it in just about any reactive program that we write.
Error handling in RxJS is likely not as well understood as other parts of the library, but it’s actually quite simple to understand if we focus on understanding first the Observable contract in general.
In this post, we are going to provide a complete guide containing the most common error handling strategies that you will need in order to cover most practical scenarios, starting with the basics (the Observable contract).
In this post, we will cover the following topics:
So without further ado, let’s get started with our RxJs Error Handling deep dive!
In order to understand error handling in RxJs, we need to first understand that any given stream can only error out once. This is defined by the Observable contract, which says that a stream can emit zero or more values.
The contract works that way because that is just how all the streams that we observe in our runtime work in practice. Network requests can fail, for example.
A stream can also complete, which means that:
As an alternative to completion, a stream can also error out, which means that:
Notice that completion or error are mutually exclusive:
Notice also that there is no obligation for the stream to complete or error out, those two possibilities are optional. But only one of those two can occur, not both.
This means that when one particular stream errors out, we cannot use it anymore, according to the Observable contract. You must be thinking at this point, how can we recover from an error then?
To see the RxJs error handling behavior in action, let’s create a stream and subscribe to it. Let’s remember that the subscribe call takes three optional arguments:
@Component({ | |
selector: ‘home’, | |
templateUrl: ‘./home.component.html’ | |
}) | |
export class HomeComponent implements OnInit { | |
constructor(private http: HttpClient) {} | |
ngOnInit() { | |
const http$ = this.http.get<Course[]>(‘/api/courses’); | |
http$.subscribe( | |
res => console.log(‘HTTP response’, res), | |
err => console.log(‘HTTP Error’, err), | |
() => console.log(‘HTTP request completed.’) | |
); | |
} | |
} | |
view raw01.ts hosted with ❤ by GitHub
If the stream does not error out, then this is what we would see in the console:
HTTP response {payload: Array(9)}
HTTP request completed.
As we can see, this HTTP stream emits only one value, and then it completes, which means that no errors occurred.
But what happens if the stream throws an error instead? In that case, we will see the following in the console instead:
As we can see, the stream emitted no value and it immediately errored out. After the error, no completion occurred.
Handling errors using the subscribe call is sometimes all that we need, but this error handling approach is limited. Using this approach, we cannot, for example, recover from the error or emit an alternative fallback value that replaces the value that we were expecting from the backend.
Let’s then learn a few operators that will allow us to implement some more advanced error handling strategies.
In synchronous programming, we have the option to wrap a block of code in a try clause, catch any error that it might throw with a catch block and then handle the error.
Here is what the synchronous catch syntax looks like:
try { | |
// synchronous operation | |
const httpResponse = getHttpResponseSync(‘/api/courses’); | |
} | |
catch(error) { | |
// handle error | |
} |
view raw02.ts hosted with ❤ by GitHub
This mechanism is very powerful because we can handle in one place any error that happens inside the try/catch block.
The problem is, in Javascript many operations are asynchronous, and an HTTP call is one such example where things happen asynchronously.
RxJs provides us with something close to this functionality, via the RxJs catchError Operator.
As usual and like with any RxJs Operator, catchError is simply a function that takes in an input Observable, and outputs an Output Observable.
With each call to catchError, we need to pass it a function which we will call the error handling function.
The catchError operator takes as input an Observable that might error out, and starts emitting the values of the input Observable in its output Observable.
If no error occurs, the output Observable produced by catchError works exactly the same way as the input Observable.
However, if an error occurs, then the catchError logic is going to kick in. The catchError operator is going to take the error and pass it to the error handling function.
That function is expected to return an Observable which is going to be a replacement Observable for the stream that just errored out.
Let’s remember that the input stream of catchError has errored out, so according to the Observable contract we cannot use it anymore.
This replacement Observable is then going to be subscribed to and its values are going to be used in place of the errored out input Observable.
Let’s give an example of how catchError can be used to provide a replacement Observable that emits fallback values:
const http$ = this.http.get<Course[]>(‘/api/courses’); | |
http$ | |
.pipe( | |
catchError(err => of([])) | |
) | |
.subscribe( | |
res => console.log(‘HTTP response’, res), | |
err => console.log(‘HTTP Error’, err), | |
() => console.log(‘HTTP request completed.’) | |
); |
view raw03.ts hosted with ❤ by GitHub
Let’s break down the implementation of the catch and replace strategy:
of([])
functionof()
function builds an Observable that emits only one value ([]
) and then it completesof([])
), that gets subscribed to by the catchError operatorAs the end result, the http$
Observable will not error out anymore! Here is the result that we get in the console:
HTTP response []
HTTP request completed.
As we can see, the error handling callback in subscribe()
is not invoked anymore. Instead, here is what happens:
[]
is emittedhttp$
Observable is then completedAs we can see, the replacement Observable was used to provide a default fallback value ([]
) to the subscribers of http$
, despite the fact that the original Observable did error out.
Notice that we could have also added some local error handling, before returning the replacement Observable!
And this covers the Catch and Replace Strategy, now let’s see how we can also use catchError to rethrow the error, instead of providing fallback values.
Let’s start by noticing that the replacement Observable provided via catchError can itself also error out, just like any other Observable.
And if that happens, the error will be propagated to the subscribers of the output Observable of catchError.
This error propagation behavior gives us a mechanism to rethrow the error caught by catchError, after handling the error locally. We can do so in the following way:
const http$ = this.http.get<Course[]>(‘/api/courses’); | |
http$ | |
.pipe( | |
catchError(err => { | |
console.log(‘Handling error locally and rethrowing it…’, err); | |
return throwError(err); | |
}) | |
) | |
.subscribe( | |
res => console.log(‘HTTP response’, res), | |
err => console.log(‘HTTP Error’, err), | |
() => console.log(‘HTTP request completed.’) | |
); | |
view raw04.ts hosted with ❤ by GitHub
Let’s break down step-by-step the implementation of the Catch and Rethrow Strategy:
[]
, we are now handling the error locally in the catchError functionIf we now run the code above, here is the result that we get in the console:
As we can see, the same error was logged both in the catchError block and in the subscription error handler function, as expected.
Notice that we can use catchError multiple times at different points in the Observable chain if needed, and adopt different error strategies at each point in the chain.
We can, for example, catch an error up in the Observable chain, handle it locally and rethrow it, and then further down in the Observable chain we can catch the same error again and this time provide a fallback value (instead of rethrowing):
const http$ = this.http.get<Course[]>(‘/api/courses’); | |
http$ | |
.pipe( | |
map(res => res[‘payload’]), | |
catchError(err => { | |
console.log(‘caught mapping error and rethrowing’, err); | |
return throwError(err); | |
}), | |
catchError(err => { | |
console.log(‘caught rethrown error, providing fallback value’); | |
return of([]); | |
}) | |
) | |
.subscribe( | |
res => console.log(‘HTTP response’, res), | |
err => console.log(‘HTTP Error’, err), | |
() => console.log(‘HTTP request completed.’) | |
); |
view raw05.ts hosted with ❤ by GitHub
If we run the code above, this is the output that we get in the console:
As we can see, the error was indeed rethrown initially, but it never reached the subscribe error handler function. Instead, the fallback []
value was emitted, as expected.
Besides a catch block for handling errors, the synchronous Javascript syntax also provides a finally block that can be used to run code that we always want executed.
The finally block is typically used for releasing expensive resources, such as for example closing down network connections or releasing memory.
Unlike the code in the catch block, the code in the finally block will get executed independently if an error is thrown or not:
try { | |
// synchronous operation | |
const httpResponse = getHttpResponseSync(‘/api/courses’); | |
} | |
catch(error) { | |
// handle error, only executed in case of error | |
} | |
finally { | |
// this will always get executed | |
} |
view raw06.ts hosted with ❤ by GitHub
RxJs provides us with an operator that has a similar behavior to the finally functionality, called the finalize Operator.
Note: we cannot call it the finally operator instead, as finally is a reserved keyword in Javascript
Just like the catchError operator, we can add multiple finalize calls at different places in the Observable chain if needed, in order to make sure that the multiple resources are correctly released:
const http$ = this.http.get<Course[]>(‘/api/courses’); | |
http$ | |
.pipe( | |
map(res => res[‘payload’]), | |
catchError(err => { | |
console.log(‘caught mapping error and rethrowing’, err); | |
return throwError(err); | |
}), | |
finalize(() => console.log(“first finalize() block executed”)), | |
catchError(err => { | |
console.log(‘caught rethrown error, providing fallback value’); | |
return of([]); | |
}), | |
finalize(() => console.log(“second finalize() block executed”)) | |
) | |
.subscribe( | |
res => console.log(‘HTTP response’, res), | |
err => console.log(‘HTTP Error’, err), | |
() => console.log(‘HTTP request completed.’) | |
); |
view raw07.ts hosted with ❤ by GitHub
Let’s now run this code, and see how the multiple finalize blocks are being executed:
Notice that the last finalize block is executed after the subscribe value handler and completion handler functions.
As an alternative to rethrowing the error or providing fallback values, we can also simply retry to subscribe to the errored out Observable.
Let’s remember, once the stream errors out we cannot recover it, but nothing prevents us from subscribing again to the Observable from which the stream was derived from, and create another stream.
Here is how this works:
The big question here is, when are we going to subscribe again to the input Observable, and retry to execute the input stream?
In order to answer these questions, we are going to need a second auxiliary Observable, which we are going to call the Notifier Observable. It’s the Notifier
Observable that is going to determine when the retry attempt occurs.
The Notifier Observable is going to be used by the retryWhen Operator, which is the heart of the Retry Strategy.
To understand how the retryWhen Observable works, let’s have a look at its marble diagram:
Notice that the Observable that is being re-tried is the 1-2 Observable in the second line from the top, and not the Observable in the first line.
The Observable on the first line with values r-r is the Notification Observable, that is going to determine when a retry attempt should occur.
Let’s break down what is going in this diagram:
r
, way after the Observable 1-2 has completedr
) could be anythingr
got emitted, because that is what is going to trigger the 1-2 Observable to be retriedr
value, and the same thing occurs: the values of a newly subscribed 1-2 stream are going to start to get reflected in the output of retryWhenAs we can see, retryWhen simply retries the input Observable each time that the Notification Observable emits a value!
Now that we understand how retryWhen works, let’s see how we can create a Notification Observable.
We need to create the Notification Observable directly in the function passed to the retryWhen operator. This function takes as input argument an Errors Observable, that emits as values the errors of the input Observable.
So by subscribing to this Errors Observable, we know exactly when an error occurs. Let’s now see how we could implement an immediate retry strategy using the Errors Observable.
In order to retry the failed observable immediately after the error occurs, all we have to do is return the Errors Observable without any further changes.
In this case, we are just piping the tap operator for logging purposes, so the Errors Observable remains unchanged:
const http$ = this.http.get<Course[]>(‘/api/courses’); | |
http$.pipe( | |
tap(() => console.log(“HTTP request executed”)), | |
map(res => Object.values(res[“payload”]) ), | |
shareReplay(), | |
retryWhen(errors => { | |
return errors | |
.pipe( | |
tap(() => console.log(‘retrying…’)) | |
); | |
} ) | |
) | |
.subscribe( | |
res => console.log(‘HTTP response’, res), | |
err => console.log(‘HTTP Error’, err), | |
() => console.log(‘HTTP request completed.’) | |
); | |
view raw08.ts hosted with ❤ by GitHub
Let’s remember, the Observable that we are returning from the retryWhen function call is the Notification Observable!
The value that it emits is not important, it’s only important when the value gets emitted because that is what is going to trigger a retry attempt.
If we now execute this program, we are going to find the following output in the console:
As we can see, the HTTP request failed initially, but then a retry was attempted and the second time the request went through successfully.
Let’s now have a look at the delay between the two attempts, by inspecting the network log:
As we can see, the second attempt was issued immediately after the error occurred, as expected.
Let’s now implement an alternative error recovery strategy, where we wait for example for 2 seconds after the error occurs, before retrying.
This strategy is useful for trying to recover from certain errors such as for example failed network requests caused by high server traffic.
In those cases where the error is intermittent, we can simply retry the same request after a short delay, and the request might go through the second time without any problem.
To implement the Delayed Retry Strategy, we will need to create a Notification Observable whose values are emitted two seconds after each error occurrence.
Let’s then try to create a Notification Observable by using the timer creation function. This timer function is going to take a couple of arguments:
Let’s then have a look at the marble diagram for the timer function:
As we can see, the first value 0 will be emitted only after 3 seconds, and then we have a new value each second.
Notice that the second argument is optional, meaning that if we leave it out our Observable is going to emit only one value (0) after 3 seconds and then complete.
This Observable looks like its a good start for being able to delay our retry attempts, so let’s see how we can combine it with the retryWhen and delayWhen operators.
One important thing to bear in mind about the retryWhen Operator, is that the function that defines the Notification Observable is only called once.
So we only get one chance to define our Notification Observable, that signals when the retry attempts should be done.
We are going to define the Notification Observable by taking the Errors Observable and applying it the delayWhen Operator.
Imagine that in this marble diagram, the source Observable a-b-c is the Errors Observable, that is emitting failed HTTP errors over time:
Let’s follow the diagram, and learn how the delayWhen Operator works:
b
shows up in the output after the value c
, this is normalb
duration selector Observable (the third horizontal line from the top) only emitted its value after the duration selector Observable of c
, and that explains why c
shows up in the output before b
Let’s now put all this together and see how we can retry consecutively a failing HTTP request 2 seconds after each error occurs:
const http$ = this.http.get<Course[]>(‘/api/courses’); | |
http$.pipe( | |
tap(() => console.log(“HTTP request executed”)), | |
map(res => Object.values(res[“payload”]) ), | |
shareReplay(), | |
retryWhen(errors => { | |
return errors | |
.pipe( | |
delayWhen(() => timer(2000)), | |
tap(() => console.log(‘retrying…’)) | |
); | |
} ) | |
) | |
.subscribe( | |
res => console.log(‘HTTP response’, res), | |
err => console.log(‘HTTP Error’, err), | |
() => console.log(‘HTTP request completed.’) | |
); | |
view raw09.ts hosted with ❤ by GitHub
Let’s break down what is going on here:
Let’s now see what this looks like in the console! Here is an example of an HTTP request that was retried 5 times, as the first 4 times were in error:
And here is the network log for the same retry sequence:
As we can see, the retries only happened 2 seconds after the error occurred, as expected!
And with this, we have completed our guided tour of some of the most commonly used RxJs error handling strategies available, let’s now wrap things up and provide some running sample code.
In order to try these multiple error handling strategies, it’s important to have a working playground where you can try handling failing HTTP requests.
This playground contains a small running application with a backend that can be used to simulate HTTP errors either randomly or systematically. Here is what the application looks like:
As we have seen, understanding RxJs error handling is all about understanding the fundamentals of the Observable contract first.
We need to keep in mind that any given stream can only error out once, and that is exclusive with stream completion; only one of the two things can happen.
In order to recover from an error, the only way is to somehow generate a replacement stream as an alternative to the errored out stream, like it happens in the case of the catchError or retryWhen Operators.
I hope that you have enjoyed this post, if you would like to learn a lot more about RxJs, we recommend checking the RxJs In Practice Course course, where lots of useful patterns and operators are covered in much more detail.
Also, if you have some questions or comments please let me know in the comments below and I will get back to you.
Source: Angular University