Custom Global Error Handling

Global Error Handler Angular:

This article is based on a walk-through of the Angular custom error handling. As we all know, Angular always surprises us. Here we have something more.

Angular provides a ErrorHandler feature to handle errors. The beauty is that, we can create this feature as a global service in our app.

Implementation Desc:
We are just implementing a service which implements ErrorHandling class; and we have to override the ErrorHandler method.

That's all, error captured.

Implementation by code:Angular error handler class is utilised for global/centralised exception handling. The default behaviour is to print the error in the console and we have to override the method. We implement this class to create a custom error handler.

class ErrorHandler {
handleError(error: any): void

ErrorHandler has a method handleError(error) that executes whenever the application throws an error anywhere in the application.

Steps 1:Create a service by implementing ErrorHandler. Override the handleError(error) method here is an example

import { Injectable, ErrorHandler } from '@angular/core';
import { HttpErrorResponse } from '@angular/common/http';

export class GlobalCustomErrorHandler implements ErrorHandler {
    handleError(error: any) {
      // custom code here
      console.log('Error captured from the centralized error handler');     

Step 2:
Configuring the GlobalCustomErrorHandler

  providers: [
    { provide: ErrorHandler, useClass: GlobalCustomErrorHandler },
export class AppModule { }

And that's it. Your error is captured by the custom handler.

Subscribe to newsletter
Need more tech news? Tune in to our weekly newsletter to get the latest updates