By
Mike Smith

Client-side error handling in Angular

AngularJS 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 logging 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 with $exceptionHandler

Uncaught exceptions in AngularJS are all funneled through the $exceptionHandler service. Fantastic! This service is very simple by design. When unmodified, $exceptionHandler sends all uncaught exceptions to the $log.error service. The $log.error service passes the error through to the client's console.

Here is the structure for an $exceptionHandler call:

$exceptionHandler(exception, [cause]);

What is this? When we call $exceptionHandler, we can pass two arguments:

  • exception: The exception associated with the error the application encountered.
  • cause: Additional context about the cause of the exception.

The second argument, cause, is entirely optional. It can be helpful when writing exception handlers or adding external handling functionality.

Extended $exceptionHandler

If we let $exceptionHandler simply run on its own and logging uncaught exceptions to the console in production isn't very useful. Fortunately, Angular has a handful of ways to extend $exceptionHandler to take more action and gather more context when errors occur.

Basic Configuration

Here is the basic configuration setup for handling with $exceptionHandler:

angular.module('exceptionOverride', []).factory('$exceptionHandler',
  function() {}
);

This code creates an Angular Module. We can extend the module by using .factory(). This is an alternative to $provider.factory() inside a chained .config() on the module.

Now that we have the base Angular code, we can actually capture some exceptions. Example:

angular.module('exceptionOverride', []).factory('$exceptionHandler',
  function() {
    return function(exception, cause) {
      exception.message += 'Angular Exception: "' + cause + '"';
      throw exception;
    };
  }
);

Augmenting your Angular error handling with Rollbar

Let's get our Rollbar on. :-) By including the popular Rollbar community notifier ng-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, we'll select JavaScript for thre language. Next, you'll receive a client-side access token which you'll need to save for later.

Don't worry about the script tag provided. We'll be installing the ng-rollbar SDK instead to use Rollbar with Angular 1.x (ng-rollbar is not currently compatible with Angular 2).

Installing ng-rollbar

Installing ng-rollbar is easy. Simply run:

bower install ng-rollbar --save

Then, include the SDK in your application with this script tag:

<script type="text/javascript" src="bower_components/ng-rollbar/ng-rollbar.min.js"></script>

Inject the library into your app.js file:

var app = angular.module('myApp', ['tandibar/ng-rollbar']);

Configuring ng-rollbar

The last thing you'll need to do is update your application's configuration:

app.config(function(RollbarProvider) {
  RollbarProvider.init({
    accessToken: "YOUR_ACCESS_TOKEN",
    captureUncaught: true,
    payload: {
      environment: 'YOUR_ENVIRONMENT'
    }
  });
});

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);

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

Manually handling errors with Rollbar

To manually handle errors, just inject Rollbar into the corresponding Angular component. This code looks something like this:

myApp.controller('MainCtrl', function($scope, Rollbar) {
  $scope.onSomeEvent = function() {
    Rollbar.error('this is an error with special handling');
  };
});

You can also flag errors by severity, so that you can make sure the most critical errors are known and handled first.

// 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

Debugging errors with data in 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. 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 AngularJS and how easy it is to get started. If you haven’t already, signup for a 14-day free trial of Rollbar and let us help you defeat annoying client-side JavaScript errors!

Comments