如何全局访问/抛出角度自定义错误?

时间:2015-06-04 06:30:57

标签: javascript angularjs error-handling

我想创建自己的自定义错误,如下所示:

function CustomError(message) {
   Error.captureStackTrace(this);
   this.message = message;
   this.name = "SomeCustomError";
}
CustomError.prototype = Object.create(Error.prototype);

我应该如何在角度中集成自定义错误?无论是在服务,控制器还是类似的情况下,我都可以在任何角度抛出相同的自定义错误。我当然不希望每次都“依赖注入”CustomError。

throw CustomError('some message');

或者,如果我在考虑,我也可以简单地说:

throw {name : "CustomError", message : "some message"};

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在我的app.js - bootstrap文件中,我现在有类似的东西:

angular.module('myApp')
    .run(['$window',
        function($window) {

            function CustomError(message) {
                Error.captureStackTrace(this);
                this.message = message;
                this.name = "SomeCustomError";
            }
            CustomError.prototype = Object.create(Error.prototype);

            $window.CustomError = CustomError;
            // From here on, I can throw it anywhere: 
            // throw new CustomError("D'oh!");
        }
    ]);