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? 📝 :

Error handling refers to the anticipation, detection, and resolution of programming, application, and communications errors.

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
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)
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}`;
return throwError(errorMsg);

- Logging Error: console log 🗒:

It can be also a simple console log message


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 📖 :

catching error

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:

source: https://rxjs.dev/api/operators/catchError

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),
  • 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.

source: http://reactivex.io/documentation/operators/retry.html

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📖:

source : https://rxjs.dev/api/operators/retryWhen

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 📓 📕 :

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 🙂




<script>alert('try your best')</script>

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Master Lists in React Native : A New Hope

Building a Web Scalable project using React and Flux - UI Kit


12 Expert Tips That I’d Like to Share as an Experienced Programmer

Firebase as simple database to React app

Setting up Reactjs using Webpack 4 and Babel 7; the Definitive Guide

Create bot for your Discord Server

We Are in the Era of JavaScript

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Rebai Ahmed

Rebai Ahmed

<script>alert('try your best')</script>

More from Medium

SPAs: from Server to Client and back

Add login to an Angular app using Asgardeo

Ionic 5 Auth Guard Implementation

Creating custom validators with NgRx Forms