By
Jason Skowronski

Custom error handling for Angular

Angular 2+ is a popular open-source JavaScript MVC framework that lets you build highly structured, testable, and maintainable front-end applications. Angular is most commonly used on single-page applications. Stable and reliable single page applications depend on solid client-side error monitoring tools and techniques. But, getting the right exception data and context isn't always easy. We're going to dive into how to capture, handle and debug Angular errors.

Error Logging in Angular 2 with ErrorHandler

ErrorHandler class provides a hook for centralized exception handling. The default implementation of ErrorHandler prints error messages to the console. This service is very simple by design. To intercept the error handling we need to write a custom handler.

Here is the structure for an ErrorHandler class in TypeScript:

class ErrorHandler {
  constructor(){}
  handleError(error: any): void
}

The handleError(error: any): void method allows you to implement your own code to do something with exception, such as recover your app gracefully or report it to an error monitoring service.

Basic configuration for implementing custom ErrorHandler in Angular 2

To understand how error handlers work, let’s start by creating a CustomErrorHandler which implements ErrorHandler

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

@Injectable()
export class CustomErrorHandler implements ErrorHandler {
  constructor() { }
  handleError(error) {
    // your custom error handling logic
    console.log(error)
  }
}

Now in our AppModule we have to add our CustomErrorHandler as a provider

import { NgModule, ApplicationRef, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ] } from './custom-error-handler';
import { AppComponent } from './app.component';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  bootstrap: [AppComponent],
  providers: [{
    provide: ErrorHandler,
    useClass: CustomErrorHandler
  }]
})
export class AppModule { }

Now any exception in our application will be caught in our CustomErrorhandler.

Angular 2 error handling with Rollbar

Let's get our Rollbar on. :-) By including the Rollbar SDK in your Angular application, errors are automatically captured, grouped and reported. And with much more contextual data than the console provides.

The first thing you'll want to do is sign up for a Rollbar account. Once you're signed up, you'll create a new Project. Since we're using Angular 4, we'll select Angular 2+ under Front-End for the language. Next, you'll receive a client-side access token which you'll need to save for later.

Angular 2

Creating an Angular 2 Project, as seen in Rollbar

Installing Rollbar

Installing Rollbar is easy. Simply run:

npm install rollbar --save

Configuring Rollbar with your Angular 2 app

The last thing you'll need to do is update your application's CustomErrorHandler, and we will rename it to RollbarErrorHandler. Remember to add your own accessToken which you received earlier!

You’ll also notice that we added a function called rollbarFactory. This creates a named factory that is necessary when using Ahead-of-Time (AOT) compilation in Angular 4+.

import * as Rollbar from 'rollbar';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { AppComponent } from './app.component';

const rollbarConfig = {
  accessToken: 'POST_CLIENT_ITEM_ACCESS_TOKEN',
  captureUncaught: true,
  captureUnhandledRejections: true,
};

export function rollbarFactory() {
  return new Rollbar(rollbarConfig);
}

@Injectable()
export class RollbarErrorHandler implements ErrorHandler {
  rollbar: any;
  constructor(private injector: Injector) {
    this.rollbar = injector.get(Rollbar);
  }

  handleError(err: any ): void {
    console.log(err);
    this.rollbar.error(err.originalError || err);
  }
}

@NgModule({
  imports: [ BrowserModule ],
  declarations: [ AppComponent ],
  bootstrap: [ AppComponent ],
  providers: [
    { provide: ErrorHandler, useClass: RollbarErrorHandler },
    { provide: Rollbar,  useFactory: rollbarFactory }
  ]
})
export class AppModule { }

You can test if everything was set up correctly by opening a console window and entering this:

window.onerror("TestRollbarError: testing window.onerror", window.location.href);

or throwing an error in an application like this:

throw new Error("Hello World, Error Message");

Once everything is installed correctly, you should see the TestRollbarError in Rollbar dashboard as below.

Rollbar dashboard for Angular exception handling

Dashboard for Angular errors, as seen in Rollbar

Manually handling errors with Rollbar

Optionally, you may decide to manually handle errors. This gives you extra control over the information passed to Rollbar. Just inject Rollbar into the corresponding Angular component. The code looks something like this:

@Component()
export class MyComponent {
  constructor(private rollbar: Rollbar) { }
  manualHandle() {
         this.rollbar.error(this.errorMessage);
  }
}

For example, you may flag errors by severity so that the most critical errors are seen and handled first. You can also pass extra data to help with debugging.

// Rollbar severities
rollbar.critical("some critical error"); // most severe
rollbar.error("some error");
rollbar.warning("some warning");
rollbar.info("some info");
rollbar.debug("some debug message"); // least severe

Sample Repository

You can find the full working code for this example on GitHub.

Debugging Angular errors with Rollbar

Now that you have Rollbar integrated into your Angular app, any errors that occur automatically get captured, grouped and reported to your new project in Rollbar. You'll be able to quickly and easily see what errors are occurring, how often they occur and the full context and analytics into all of your exceptions. You can set alert notifications on any of the errors which can be delivered to your email. Rollbar collects a wide variety of context data for each error, including detailed stack traces, request params, URL, environment, affected users, browser, location, host and much more. I hope this was a helpful intro on error handling in Angular 4 and how easy it is to get started.

For monitoring Angular 1.x exceptions with Rollbar check out ng-rollbar on GitHub.


If you haven’t already, signup for a 14-day free trial of Rollbar and let us help you take control of pesky Angular 2 errors. :-)

Join Our Community

Get the latest updates, tutorials and more, delivered to your inbox, once a month.

Comments