25

I'm trying to implement a very standard task: when an exception occurs, redirect to my /error page.

In a simplified form the code looks like this:

app.factory('$exceptionHandler', ['$location', function($location) {
    return function(exception, cause) {
        $location.path("/error");
    };
}]);

However, AngularJS complains: Circular dependency found: $location <- $exceptionHandler <- $rootScope

This looks like a fundamental limitation, not to allow use of $location when handling exceptions.

But how else can we do it then?

Rob
  • 26,989
  • 16
  • 82
  • 98
vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • According to the [docs](http://code.angularjs.org/1.2.0-rc.3/docs/api/ng.$location), the only dependencies for `$location` are `$browser`, `$sniffer` and `$rootElement`. I don't see why this code would throw this error... sorry, I'm not much help. There must be some hidden dependency that isn't in the docs... – tennisgent Oct 24 '13 at 02:02

1 Answers1

46

To get around this you need to call the $injector manually to resolve the dependency at runtime:

app.factory('$exceptionHandler', ['$injector', function($injector) {

    var $location;

    return function(exception, cause) {
        $location = $location || $injector.get('$location');
        $location.path("/error");
    };
}]);
tasseKATT
  • 38,470
  • 8
  • 84
  • 65