Learn Error Handling in Angular with RxJS, catchError, HttpInterceptor

Learn Error Handling in Angular with RxJS, catchError, HttpInterceptor

Learn Error handling in Angular 8/9, we will take the best approach with RxJS catchError / catchError operators and HttpInterceptor to handle client-side errors gracefully.

Learn Error handling in Angular 8/9, we will take the best approach with RxJS catchError / catchError operators and HttpInterceptor to handle client-side errors gracefully.

A proper Error handling makes an application most helpful for users from the user experience aspect. Error handlers report a user correctly what causing the problem vise verse. It also notifies developers in the development phase about the error reason, which assists them to fix it before it goes live.

These days new technologies are growing faster than ever. This competition is all about making a piece of software better for users be it a final user, product owner or a developer who is building it from scratch. Due to this, user experiences became the trend.

There are two types of errors which might occur in an application, inside errors and outside errors.

Outside Errors: These errors often occur from the server-side and usually starts with (5xxx) status code. These errors return the error message with the proper reason so identifying these errors is easy.

Inside Error: When something unexpected happens, then these errors are thrown. These errors occur with the proper message, which contains the reason for the error occurrence.

Here is the complete List of HTTP status codes.

Next, we practically understand how to handle client-side errors in Angular. A Client-side error handling is one of the features among other various features for developing a user friendly application.

A user gets frustrated when suddenly an app stopped working, and the user doesn’t find the reason for it. It downgrades the overall user experience of the application. To enhance the user experience, we must properly handle errors.

We will use the regular error handling approaches such as handling errors with RxJS operators catchError and throwError and managing errors with HttpClient and HttpInterceptor.

Handle Errors in Angular with HttpClient and RxJS

The simplest way to handle errors in Angular is to use Angular’s HttpClient service along with RxJS operators throwError and catchError. Http request is made, and it returns the data with a response if anything wrong happens then it returns an error object with error status code.

Below is the service in which we used the handleError() function to handle errors in Angular.

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { retry, catchError } from 'rxjs/operators';

class Post {
    constructor(
        public id: string,
        public title: string,
        public body: string
    ) { }
}

@Injectable({
    providedIn: 'root'
})

export class PostService {
    private endpoint = 'https://jsonplaceholder.typicode.com/xyz';

    constructor(private http: HttpClient) { }

    getPost(): Observable<Post[]> {
        return this.http.get<Post[]>(this.endpoint)
            .pipe(
                retry(1),
                catchError(this.handleError)
            );
    }

    handleError(error) {
        let errorMessage = '';
        if (error.error instanceof ErrorEvent) {
            // client-side error
            errorMessage = `Error: ${error.error.message}`;
        } else {
            // server-side error
            errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
        }
        console.log(errorMessage);
        return throwError(errorMessage);
    }
}

Angular 8/9 Error Handling

In the service, we defined the handleError() method. In this method, we are checking if the error is an instance of ErrorEvent. This function returns either the client-side or server-side error. This error is useful for a single service. Still, when it comes to managing multiple services, then we have to update the handleError function in every service even for a minor change.

Error Handling with HttpClient and HttpInterceptor

To handle errors properly HttpInterceptor is the best way, It intercepts Http request. It helps in converting http request before sending and after getting the response from the server. It is better used for updating data format, setting up headers, adding auth tokens etc. HttpInterceptor service offers better way to systematically handle errors in an Angular app.

The following ErrorIntercept service can manage multiple services. We are using retry(1) and catchError RxJS operators to check the HttpErrorResponse. This code is centralised in nature and can be managed from one place by far this has been the best way to manage errors in Angular.

Add the following code in error.interceptor.ts:

import {
    HttpEvent,
    HttpHandler,
    HttpRequest,
    HttpErrorResponse,
    HttpInterceptor
} from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, retry } from 'rxjs/operators';

export class ErrorIntercept implements HttpInterceptor {
    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        return next.handle(request)
            .pipe(
                retry(1),
                catchError((error: HttpErrorResponse) => {
                    let errorMessage = '';
                    if (error.error instanceof ErrorEvent) {
                        // client-side error
                        errorMessage = `Error: ${error.error.message}`;
                    } else {
                        // server-side error
                        errorMessage = `Error Status: ${error.status}\nMessage: ${error.message}`;
                    }
                    console.log(errorMessage);
                    return throwError(errorMessage);
                })
            )
    }
}

Import HttpClientmodule, HTTP_INTERCEPTORS and ErrorIntercept in app.module.ts, next inject the HTTP_INTERCEPTORS and ErrorIntercept in providers array along with that set multi: true.

import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { ErrorIntercept } from './error.interceptor';

@NgModule({
  declarations: [...],
  imports: [
    HttpClientModule
  ],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ErrorIntercept,
      multi: true
    }
  ],
  bootstrap: [...]
})

export class AppModule { }

Here is the post.service.ts:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

class Post {
    constructor(
        public id: string,
        public title: string,
        public body: string
    ) { }
}

@Injectable({
    providedIn: 'root'
})

export class PostService {
    private endpoint = 'https://jsonplaceholder.typicode.com/xyz';

    constructor(private http: HttpClient) { }

    getPost(): Observable<Post[]> {
        return this.http.get<Post[]>(this.endpoint)
    }
}

Conclusion

Finally we have completed error handling tutorial with examples, I hope this tutorial help you to understand the basic concept of handling client-side errors in Angular 8/9 with RxJS operators and HttpInterceptor.

angular web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Wondering how to upgrade your skills in the pandemic? Here's a simple way you can do it.

Corona Virus Pandemic has brought the world to a standstill. Countries are on a major lockdown. Schools, colleges, theatres, gym, clubs, and all other public

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.