Creating Global Error Handler in Angular 8

0
6106
views

Global Error Handler : At some point in our project development work we feel the need to handle all the errors of API calls at one place. Whether it may be for different status codes or for the just normal error response.

Subscribing to the API call and catching the error for each API call is tedious and repetitive work, most of the time all the errors are same.

If you feel the need of handling error in the catch block itself for few API calls you can do it, for those API call errors global error handler will simply ignore them and will handle the errors for the rest of the API calls.

import { ErrorHandler, Injectable, Injector, NgZone } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import { NotificationService, ModalWindowService, BciSidebarService } from '@bci-web-core/core';
import { Router } from '@angular/router';
import { AuthService } from '../auth.service';


@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
    constructor(private injector: Injector, private modalWindowService: ModalWindowService, private zone: NgZone) {

    }

    handleError(error: any) {
        console.log(error);
        const chunkFailedMessage = /Loading chunk [\d]+ failed/;

        if (chunkFailedMessage.test(error.message)) {
          window.location.reload();
        }
        const notificationService = this.injector.get(NotificationService);
        const router = this.injector.get(Router)
        const auth = this.injector.get(AuthService)
        if (error instanceof HttpErrorResponse) {

            if (!navigator.onLine) {
                return notificationService.error('No Internet Connection');
            }
            else {

                if (error.status == 0) {
                    return notificationService.error('Something went wrong with the server. Please try after sometime.', false, null, 5000);

                }

                if (error.status == 401) {
                    // window.sessionStorage.clear()
                    //auth.logout();
                    //window.location.href = '/login'
                    this.zone.run(() => router.navigate(["/login"]))
                    return notificationService.error(`${error.statusText}`, false, null, 5000);
                }

                else {
                    return notificationService.error(`${error.status} - ${error.statusText}`, false, null, 5000);
                }

            }
        }
        else {
            console.log(error)
            notificationService.error('Client Error. Please try after sometime.', false, null, 5000);
        }

    }

}

As you can see in the above code GLobalErrorHandler class implements ErrorHandler from @angular/core. This class implements a method handleError which receives error as parameter. Whenever error occurs in API calls or somewhere it catches.

As you go down further in the code we are putting if conditions for error types whether it is instanceof HttpErrorResponse or some front end code break errors.

This way you can handle all the errors at one common place take appropriate measures for them.

This Global Error Handler file you need to include it in the app.module.ts file providers array

providers: [AuthService, PasswordValidator,
    {
      provide: HTTP_INTERCEPTORS,
      useClass: AuthenticationInterceptor,
      multi: true
    },
    {
      provide: ErrorHandler,
      useClass: GlobalErrorHandler,
    },
    {
      provide: HTTP_INTERCEPTORS,
      useClass: HttpErrorInterceptor,
      multi: true
    }
  ],

Refer the above code block for mentioning it in the providers array.

I hope this will be helpful