如何正确覆盖angularjs中的exceptionHandler?

时间:2013-05-10 18:57:15

标签: javascript angularjs

对于某个应用,我使用的骨架与https://github.com/angular/angular-seed非常相似。

我在services.js中尝试过类似的东西:

'use strict';

/* Services */

angular.module('mApp.services', []).
  factory('$exceptionHandler', function () {
    return function (exception, cause) {
        alert(exception.message);
    }
});

这没有做任何事情,它似乎没有覆盖exceptionHandler。

如果我尝试:

var mod = angular.module('mApp', []);

mod.factory('$exceptionHandler', function() {
  return function(exception, cause) {
    alert(exception);
  };
});

它会覆盖整个应用程序。

如果我使用类似于默认角度应用的骨架,如何正确覆盖exceptionHandler?

2 个答案:

答案 0 :(得分:2)

如果没有看到你的应用程序的其余内容,很难确定,但我猜angular.module('myApp').factory( ...会起作用。如果省略第二个参数(,[]),angular将检索现有模块以进行进一步配置。如果保持角度,则会创建一个新模块。

答案 1 :(得分:0)

试试这个例子

http://jsfiddle.net/STEVER/PYpdM/

var myApp = angular.module('myApp', ['ng']).provider({

    $exceptionHandler: function(){
        var handler = function(exception, cause) {
            alert(exception);
            //I need rootScope here
        };

        this.$get = function() {
            return handler;
        };
    }
});

myApp.controller('MyCtrl', function($scope, $exceptionHandler) {
    console.log($exceptionHandler);
    throw "Fatal error";
});