Angular 5 Custom ErrorHandler

How to Create a Custom ErrorHandler?

How to create a custom ErrorHandler?
The best way to log exceptions is to provide a specific log message for each possible exception. Always ensure that sufficient information is being logged and that nothing important is being excluded.

The multiple steps involved in creating custom error logging in Angular -
1.           Create a constant class for global error messages.
2.           Create an error log service – ErrorLoggService.
3.           Create a global error handler for using the error log service for logging errors.

Steps 1 – In the first step, we will create a constant class for logging global error messages and its look like this.
export class AppConstants {
  public static get baseURL(): string { return 'http://localhost:4200/api'; }
  public static get httpError(): string { return 'There was an HTTP error.'; }
  public static get typeError(): string { return 'There was a Type error.'; }
  public static get generalError(): string { return 'There was a general error.'; }
  public static get somethingHappened(): string { return 'Nobody threw an Error but something happened!'; }
}

Steps 2 – In the second steps, we will create an error log service (ErrorLoggService) for error logging and it look like this.
import { Injectable} from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';
import{ AppConstants} from '../app/constants'

//#region Handle Errors Service
@Injectable()
export class ErrorLoggService {

  constructor() {  }

  //Log error method
  logError(error: any) {
    //Returns a date converted to a string using Universal Coordinated Time (UTC).
    const date = new Date().toUTCString();

    if (error instanceof HttpErrorResponse) {
      //The response body may contain clues as to what went wrong
      console.error(date, AppConstants.httpError, error.message, 'Status code:',
                (<HttpErrorResponse>error).status);
    }
    else if (error instanceof TypeError) {
      console.error(date, AppConstants.typeError, error.message, error.stack);
    }
    else if (error instanceof Error) {
      console.error(date, AppConstants.generalError, error.message, error.stack);
    }
    else if(error instanceof ErrorEvent){
      //A client-side or network error occurred. Handle it accordingly
      console.error(date, AppConstants.generalError, error.message);
    }
    else {
      console.error(date, AppConstants.somethingHappened, error.message, error.stack);
    }
  }
}
//#endregion

Steps 3 – In the 3rd steps, we will create a global error handler for using the error log service for logging errors and its look like this.
import { Injectable, ErrorHandler } from '@angular/core';
import {ErrorLoggService} from './error-logg.service';

// Global error handler for logging errors
@Injectable()
export class GlobalErrorHandler extends ErrorHandler {
    constructor(private errorLogService: ErrorLoggService) {
       //Angular provides a hook for centralized exception handling.
       //constructor ErrorHandler(): ErrorHandler
        super();
    }

    handleError(error) : void {
        this.errorLogService.logError(error);
    }
}
Steps 4 – In the 4th step, we will Import global handler and error handler services in the NgModule and its look like this.
import {ErrorLoggService} from './error-logg.service';
import {GlobalErrorHandler} from './global-error.service';

//AppModule class with @NgModule decorator
@NgModule({
  //declarations is used for configure the selectors
  declarations: [
    AppComponent,
  ],
  //Composability and Grouping
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  //Runtime or injector configuration
  //Register global error log service and error handler
  providers: [ErrorLoggService, GlobalErrorHandler],
  //bootstrapped entry component
  bootstrap: [AppComponent]
})
export class AppModule { }

Steps 5 – Finally, we got a custom error handler for log error in your application errors.

What Happens If the Request fails on the Server Due to Poor Network Connection?
HttpClient will return an error instead of a successful response.

ANIL SINGH

Anil Singh is an author, tech blogger, and software programmer. Book writing, tech blogging is something do extra and Anil love doing it. For more detail, kindly refer to this link..

My Tech Blog - https://www.code-sample.com/
My Books - Book 1 and Book 2

How to Create a Custom ErrorHandler? How to Create a Custom ErrorHandler? Reviewed by Anil Singh on 12:19 AM Rating: (5)
www.code-sample.com/. Powered by Blogger.
^