$exceptionHandler decorator on strictdi - circular and strictdi errors

770 views Asked by At

I'm having trouble with formatting my $exceptionHandler to strictdi. I'm trying to modify the exceptionhandler in order to log angular errors to our servers and let us know certain pages crash. For the code below, I am having circular dependency errors. On the next set of code, I get strictdi errors. Please note we minify our code with gulp.

error here: Circular dependency found: $rootScope <- $http <- serverlog <- $exceptionHandler <- $rootScope


var pageApp = angular.module('pageApp',['angular-oauth2','ngCookies']);

pageApp.factory("serverlog", serverlog);
serverlog.$inject = ["$http"];
function serverlog($http) {
    var svc = {};
    svc.add = function(exception) {
        var data = angular.toJson(exception);
        console.log("Sending to server errors");
        // console.log(data);
        // $.ajax({
        //  type: "POST",
        //  url: "/api/v1/jslog",
        //  contentType: "application/json",
        //  data: data
        // });
    };
    return svc;
}

pageApp.config(['$provide', function($provide) {
    $provide.decorator("$exceptionHandler", $exceptionHandler);
    $exceptionHandler.$inject = ['$delegate','serverlog'];
    function $exceptionHandler($delegate,serverlog) {
        return function(exception, cause) {
            $delegate(exception, cause);
            serverlog.add(exception);
        }
    };
}]);

Then for this set of code, comes the strictdi errors : serverlog is not using explicit annotation and cannot be invoked in strict mode

pageApp.config(['$provide', function($provide) {
  $provide.decorator("$exceptionHandler", ['$delegate','serverlog', function($delegate,serverlog) {
    return function(exception, cause) {
        $delegate(exception, cause);
        serverlog.add(exception);
    }
  }]);
}]);
1

There are 1 answers

1
tasseKATT On BEST ANSWER

To solve the circular dependency you can inject $injector instead of serverlog and resolve the dependency at runtime instead:

pageApp.config(['$provide', function($provide) {

  $provide.decorator("$exceptionHandler", $exceptionHandler);
  $exceptionHandler.$inject = ['$delegate', '$injector'];

  function $exceptionHandler($delegate, $injector) {

    var serverlog;

    return function(exception, cause) {

      serverlog = serverlog || $injector.get('serverlog');

      $delegate(exception, cause);
      serverlog.add(exception);
    };
  }
}]);

Tried the second example, but couldn't replicate the strictdi error. Should give the same error as the first example as long as you are using the same code for the serverlog service.