Custom exception handling in angularJS

Exception handling is one of the key features of any development effort. It does not matter what language or platform you are using on client side or server side development, exception and error handling and reporting is one of the first tasks that I implement. I tried to deviate a little bit when I was trying to put together some quick features using angularJS and it bit me hard.

After I made some change to existing angular implementation, I noticed that none of angularJS directives were resolving on my pages. I spent lot of time trying to track down the error and was not getting anywhere. Then I realized that somewhere there is error that is preventing angularJS to attach. And this error is getting consumed somehow.

$exceptionHandler service

$exceptionHandler is at heart of all the angularJS related exception handling. If you read the documentation, it clearly says that default behavior is to report all errors to browser console using $log service. Lot of time we forget that browser console may be first place to look for any messages that are being thrown at us.

Custom $exceptionHandler

A very quick way to handle this is my providing your own implementation of $exceptionHandler. It is very straight forward to write this custom exception handler. You can simply take the sample provided in documentation and use it as starting point. Following code sample shows how I incorporated this in my own implementation.

var SchedulerDashboard = angular.module("SchedulerDashboardApp", []);
SchedulerDashboard.factory('$exceptionHandler', function () {
  return function (exception, cause) {
  exception.message += ' (caused by "' + cause + '")';
  throw exception;
  };
});

Now every time an exception is thrown from angularJS it will get caught in this custom implementation. As the documentation states, this custom exception handler will now throw a hard exception. You can modify this implementation to log the error to your server or whatever best suites architecture of your application.

One this you will notice is that this custom exception handler is associated with a module. So if your controller is not part of the module then custom exception handler will not be invoked. So you have to make sure that you have provided custom $exceptionHandler at the right level for right module.

comments powered by Disqus

Blog Tags