【问题标题】:How to use $http.post within global error handling?如何在全局错误处理中使用 $http.post?
【发布时间】:2014-11-11 15:30:49
【问题描述】:

我有一个带有 AngularJS 1.3 单页应用程序组件的 MVC 5.0 Web 项目。如果出现任何未处理的角度异常,我想发回 MVC 控制器,所以我是 overriding the $exceptionHandler factory,如下所示:

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

在 Chrome 中,Javascript 控制台报告“未捕获的错误:[$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" 当我加载包含此脚本的页面时。显然,$http 已经对 $exceptionHandler 有依赖,所以我不能给 $exceptionHandler 对 $http 的依赖,因为这会创建一个循环依赖。

我想我可以使用 jQuery.ajax,但如果存在的话,我更喜欢更角度的解决方案。有人有吗?

【问题讨论】:

    标签: angularjs angularjs-http


    【解决方案1】:

    您可以使用 $injector 服务并查找 $http 服务:

    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
            });
        };
    

    【讨论】:

    • 做到了。谢谢!
    • 这行得通,但就我而言,我不得不使用exception.toString(),因为exception 看起来不像是一个普通的字符串(无论如何在AngularJS 1.5 中)。
    猜你喜欢
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    • 2019-05-21
    • 2022-08-21
    • 1970-01-01
    • 2019-02-03
    相关资源
    最近更新 更多