How to use $http.post within global error handling?

554 Views Asked by At

I have an MVC 5.0 web project with AngularJS 1.3 single page app components. I want to post back to the MVC controller in the event of any unhandled angular exceptions, so I'm overriding the $exceptionHandler factory like this:

    mod.factory('$exceptionHandler', ['$http', function($http) {
    return function(exception, cause) {
        console.log(exception.message);
        $http.post("Application/CatchAngularError", {
            exception: exception,
            cause: cause
        });
    }
}]);

In Chrome, the Javascript console reports "Uncaught Error: [$injector:cdep] http://errors.angularjs.org/1.3.0/$injector/cdep?p0=%24rootScope%20%3C-%20%24http%20%3C-%20%24exceptionHandler%20%3C-%20%24rootScope" when I load a page including this script. Evidently, $http already has a dependency on $exceptionHandler, so I can't give $exceptionHandler a dependency on $http, because this creates a circular dependency.

I guess I can use jQuery.ajax, but I'd prefer a more angular solution if one exists. Anybody have one?

1

There are 1 best solutions below

1
On BEST ANSWER

You could use the $injector service and lookup the $http service:

mod.factory('$exceptionHandler', ['$injector', function($injector) {
    return function(exception, cause) {
        console.log(exception.message);
        var $http = $injector.get('$http');
        $http.post("Application/CatchAngularError", {
            exception: exception,
            cause: cause
        });
    };