Rxjs Heaven (Part1: Error handling )

Introduction 🚩 :
Hello Dear Readers
Making everything reactively is a trend in web development currently with the most famous JS frameworks not only with Angular! so I decided to start a series of blogs about Rxjs 🔥 (A reactive programming library) and cover the most use cases with code examples to help you clearly understand why I called Rxjs a Heaven ☀️
This series of blogs will contain :
- Part1: Error Handling With Rxjs
- Part2: Multi-Casting Operators with Rxjs ( coming soon ⏳)
- Part3: Higher-order operators with Rxjs ( coming soon ⏳)
- Part4: Custom operators with Rxjs ( coming soon ⏳)
Each part will contain an explanation for the operators, code _examples, and the most use cases for each one
Happy reading :)
What is Error-handling? 📝 :

There are a lot of error handling strategies are provided by Angular for example :
- Global Error Handler 🛠:
It’s a centralized exception handling with ErrorHandler.
class MyErrorHandler implements ErrorHandler {
handleError(error) {
// do something with the exception
}
}@NgModule({
providers: [{provide: ErrorHandler, useClass: MyErrorHandler}]
})
class MyModule {}
- HTTP Error Interceptors 🚥 :
A way to intercept HTTP requests and responses to transform or handle them before passing them along. so it can be used specifically to handle errors
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';export class HttpErrorInterceptor implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request)
.pipe(
catchError((error: HttpErrorResponse) => {
let errorMsg = '';
if (error.error instanceof ErrorEvent) {
console.log('this is client side error');
errorMsg = `Error: ${error.error.message}`;
}
else {
console.log('this is server side error');
errorMsg = `Error Code: ${error.status}, Message: ${error.message}`;
}
console.log(errorMsg);
return throwError(errorMsg);
})
)
- Logging Error: console log 🗒:
It can be also a simple console log message
console.log(errorMsg);
Error handling With Rxjs 🔥 💥:
The previous section described the defined error handling strategies provided by Angular.
Now let’s go deep with the Rxjs most used operators for error dealing with 🔎
“When an error occurs, it’s game over, the observable completes and you cannot recover from it.! “
Scenario: if the error gets emitted by the observable, there will be no more new values emitted because it will be considered as “broken”
So we need to handle it ☑️!
(A) The catchError Operator 📖 :

We will start with the catchError operator, it can be used to handle the errors thrown by the Angular Observable, by returning a new Observable
or throwing user-defined error:

The catchError operator takes as input an Observable that might error out and starts emitting input Observable values as an output
Code-Example 📘:
Code-Explanation 📘:
When the source observable ( HTTP observable in the example )error is thrown, we will have different scenarios that we can implement :
- mapping the error to a new observable : (
Of([])
for example )
catchError((err) => of([]))
- retry the caught source Observable again in case of error : (
take(30)
) for example) :
catchError((err, caught) => caught),
take(30))
- throw a new error 💥 ( see next section 🗂)
(B) throwError operator 📖:

As we said in the previous section we can throw an error caught by using the throwError(err)
the operator provided by Rxjs that will return an observable, which will emit an error notification
Code-Example 📘:
Code-Explanation 📘:
When an error occurred, it will be caught and we will return a new observable, which emit an error notification
Used more for code readability
(C) The retry Operator 📖:

The retry(retry_count: number): Observable operator can be useful for retrying HTTP requests!
Usage 🚩 :
It can happen for example a network request failed due to an internet connection issue or other HTTP errors reasons, so it can be useful to implement a retry action.
Code-Example 📘 :
Code-Explanation 📘:
retry(1)
it will be used to retry for one time a failed network request (for HTTP GET USERS)
(D) The retryWhen operator📖:

Retry an observable sequence on error based on custom criteria
Usage 🚩 :
used until success or max number of attempts reached!
Code-Example 📘 :
Code-Explanation 📘:
retryWhen( crietria)
- it will repeat the source sequence observable when an error occurred
- count how many times the error occurred
- if it’s more than 2 times so throw an error
(E) The finalize Operator 📖:
the “finalize” operator consists in the “finally { … }” clause. like try-catch-finally
it will be called when the observable completes or errors
Code-Example 📘 :
Code-Explanation 📘:
finalize()
it will be executed when the observable is complete ✅
One case to using this operator is: “Disabling/enabling button when making an HTTP request “
-References 📓 📕 :
- https://www.tektutorialshub.com/angular/angular-http-error-handling/
- https://www.tektutorialshub.com/angular/angular-http-error-handling/ fi catch error in service
- https://www.positronx.io/angular-error-handling-tutorial-with-examples/
- https://www.pluralsight.com/guides/handling-exceptions-using-the-angular-httpclient
- https://medium.com/mayankvamja/api-error-handling-in-angular-9-with-rxjs-6-part-2-of-guide-to-deal-with-apis-in-angular-302b44612d2b
- https://blog.angular-university.io/rxjs-error-handling/
- https://pkief.medium.com/global-error-handling-in-angular-ea395ce174b1
- https://www.tektutorialshub.com/angular/using-throwerror-in-angular-observable/
- https://xgrommx.github.io/rx-book/content/observable/observable_instance_methods/retrywhen.html
Conclusion ❤️👏:
In conclusion, we made a step to discover the reactive error handling strategies with Rxjs and the most used operators ( catchError (),throwError() , retry(),retryWhen() , finalize ()) with some code examples and explanation .
I hope it helps and you enjoyed it 😀
If you liked this post feel free to leave a 👏, and follow me on Twitter and Github
Thanks 🙂