AngularJS quick tip #2 : Catch Internal Exceptions

We don't like to see our console painted in red.
But when AngularJS throw an exception, we can't catch it unless we patch the source code (and we don't want to it..).
So how can we catch Angular internal exceptions?
Read on..

Peeking into the AngularJS source code reveals that every try/catch block delegates the error to a service called $exceptionHandler.

example (line 20587):

  this.$$writeModelToScope = function() {
    ngModelSet(ctrl.$modelValue);
    forEach(ctrl.$viewChangeListeners, function(listener) {
      try {
        listener();
      } catch (e) {
        $exceptionHandler(e);
      }
    });
  };

In production, we usually don't want these errors to appear in the client console. Instead, we prefer to send them to a log server for further analysis (for example).
To do this, we can use a decorator method to override the $exceptionHandler service, and delegate the error to our own service for further handling.

The decorator will look like this:

(function () {
    /**
     * override the core $exceptionHandler service
     *
     * @desc decorate
     * @param $delegate
     * @returns {Function}
     */
    function exceptionHandlerDecorator ($delegate) {

        $delegate = function (excpetion, couse) {
            // delegate to your own service
            console.log(excpetion, couse);
        };
        return $delegate
    }

    /**
     * register a decorator
     * @param $provide
     */
    function utilModuleConfiguration ($provide) {
        $provide.decorator('$exceptionHandler', exceptionHandlerDecorator)
    }

    angular.module('utils')
        .config(['$provide', utilModuleConfiguration])
}());

I suggest using the $exceptionHandler in your code as well. It provides a central service that catches and handles errors in the app, whether it's an angular exception, or our own.