Global Error Handling in Angular – Step by Step
Angular Global Error Handling

Global Error Handling in Angular – Step by Step

Global error handling in Angular is a serious matter that is often ignored. Do you use try/catch blocks in your Angular components, services or directives?

No matter how much experience you have or how rockstar of a developer you are, errors do and will occur in applications.

As a developer, you need to ensure that your applications handle errors in a consistent manner. When your Angular application crashes or the users keep getting errors that you can’t reproduce, you will be responsible. In this post, we will look at how we can best implement global error handling in Angular application.

Throw and Try to Catch

Like most programming languages, JavaScript offers basic error handling features like try catch & finally. When used properly, these keywords can help a developer protect an application. In the example below, we try the save the world. That immediately fails as you’d expect and we catch the error. Finally, regardless of what happens in try/catch, we cleanup after ourselves.

try {
   // Save the world (fails immediately)
}
catch(err) {
  // Log the error and display message 
} 
finally {
  // Cleanup
}

While I suggest you use the above pattern for custom error handling, it does not help us catch all errors.

Global Error Handler

We will use Angular’s dependency injection mechanism to plug-in our global error handler. Create an injectable class that implements the built-in ErrorHandler. If you don’t have a project yet, look at my blog post on how to get started with Angular 7.

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

@Injectable()
export class GlobalErrorHandler implements ErrorHandler {

    constructor() { }

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

        // Log  the error
        console.log(err);

        // Optionally send it to your back-end API
        // Notify the user
    }
}

The core ErrorHandler gives us a handleError() event with all the details about the error. 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. I recommend using NGXLogger for real-world applications as it makes it very simple to log to your back-end API. The last thing you need to do is tell Angular to use our custom ErrorHandler by adding it to the providers array. 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, 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:

Do you use a similar approach? Drop a comment below and let me know!

The full project code is available on GitHub.

Umut Esen

Umut is a certified Microsoft Certified Solutions Developer and has an MSc in Computer Science. He is currently working as a senior software developer for Royal London. He is the primary author and the founder of onthecode.

Leave a Reply

Close Menu

Free Template

Get your Angular Material application template to kick-start your next project.