Error Handling in Angular 8/9 Tutorial with Examples

By Digamber Rawat Last updated on
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, and 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 a better way to handle errors in an Angular app systematically.

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 the error handling tutorial with examples. I hope this tutorial helps you to understand the basic concept of handling client-side errors in Angular 8/9 with RxJS operators and HttpInterceptor.

Digamber Rawat
Digamber Rawat

Full stack developer with a passion for UI/UX design. I create beautiful and useful digital products to solve people’s problem and make their life easy.

Thanks for checking this tutorial out :) Let me know if you have any suggestions or issue related to this tutorial, or you want to request a new tutorial. Just shoot me a mail here.