How to Implement Global Error Handling in Angular

Global error handling is one of the first things I implement in a new project. It helps avoid repetitive try/catch blocks in Angular components, services or directives. It gives me confidence that all errors will be captured consistently.

Create error handler

First things first, let’s create a new class to handle global errors.

import { ErrorHandler, Injectable } from '@angular/core';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

    handleError(error: Error) {
        const err = {
            message: error.message ? error.message : error.toString(),
            stack: error.stack ? error.stack : ''
        };

        // Log the error to browser console
        console.log(err);
        // Strongly consider sending it to backend API
        // Notify the user
    }
}

We will use Angular’s dependency injection mechanism to plug-in our global error handler.

Our error handler class above implements ErrorHandler interface, which gives us a way to use handleError().

This makes our job pretty easy, we just construct a json object with the important bits of the error and log it to the console.

At this point, you can decide what to do with the error.

The last thing we need to do is tell Angular to use our global error handler in the root module of our app.

You only need to register it once in your app.module or core.module.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { AppComponent } from './app.component';
import { GlobalErrorHandler } from './globar-error.handler';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [
{
provide: ErrorHandler,
useClass: GlobalErrorHandler
}
],
bootstrap: [AppComponent]
})
export class AppModule { }

With all of the wiring done, let’s throw a new error in the main app.component:

export class AppComponent {
  constructor() {
    throw new Error('Required');
  }
}

When you run the app, you will notice that our global error handler has logged the error in the console:

So that’s how you implement global error handling in Angular.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *