In this post, we will 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 } }
Code language: TypeScript (typescript)

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.

I recommend using NGXLogger or Application Insights to persist the details somewhere remote such as a database.

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 { }
Code language: TypeScript (typescript)

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'); } }
Code language: TypeScript (typescript)

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

global error handling in angular

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

If you found this useful, let me know in the comments below!

Check out the source code on GitHub.

Umut Esen

I am a software developer and blogger with a passion for the world wide web.

Leave a Reply