如何在angular中全局访问/抛出自定义错误

How to globally access/throw a custom error in angular?

本文关键字:自定义 错误 访问 全局 angular      更新时间:2023-09-26

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

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

我应该如何在角集成自定义错误?我可以在angular中的任何地方抛出相同的自定义错误,无论是在服务、控制器还是类似的地方。我当然不想每次都"依赖注入"CustomError。

throw CustomError('some message');

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

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

任何想法吗?

在我的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!");
        }
    ]);