How do I set up custom error handling with AngularJS?

So you want to set up some custom code to deal with errors happening in your Angular application? Well, it turns out that this is superficially simple to set up, but like we've seen with other frameworks, it won't catch all errors thrown by our app unless we also set up a global error handler in the browser. We'll go through this below.

The error handler

To set up your custom error handler, simply register a function for the $exceptionHandler name.

var app = angular.module('myApp', [...]);,
app.factory('$exceptionHandler', function() {
    return function(error, cause) {
        /* your error handling here */
    };
})

This innermost function will be called for every exception that Angular catches.

What this doesn't catch

This handler will only trigger for errors that are thrown when there is AngularJS code further up the call stack to catch it. This means that event handlers and async functions (like setTimeout(), setInterval(), callbacks) will not trigger this error handler.

To really catch everything it is necessary to add a global error handler in the browser, by setting the onerror property on the window object.

window.onerror = function(msg, src, lineno, colno, error) { /*your code*/ }

(What arguments are actually passed here will vary by browser.)

How to log every error that happens on the client

If you want to log the errors that happen in your users browser, you can do this simply by linking the catch.js script.

<script src="//cdn.catchjs.com/catch.js"></script>

By default, AngularJS will swallow the errors that it catches, so to log them as well, simply add the following error handler.

var app = angular.module('myApp', []);,
app.factory('$exceptionHandler', function() {
    return function(error, cause) {
        console.error(error); // this notifies CatchJS of the error
    };
})

For the errors that happen outside of the Angular context, there is no need to do anything. CatchJS automatically instruments the browser with a global error handler.