2015-06-04 54 views
0

我想創建自己的自定義錯誤,這樣的事情:如何全局訪問/拋出角度自定義錯誤?

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

有什麼想法?

+0

如果我理解正確的話,你想覆蓋默認的異常處理?如果是這樣,請查看文檔:https://docs.angularjs.org/api/ng/service/$exceptionHandler。看來你也可以添加功能,同時保留使用裝飾器的原始異常處理功能:http://stackoverflow.com/questions/13595469/how-to-override-exceptionhandler-plerimentation –

+0

不,我已經這樣做了。我只是想定義自己的自定義錯誤,並且我不知道如何使它成爲全局可用的角度。 – sl3dg3

+0

嗯,好像有一個選項創建,然後將服務添加到rootScope,所以你不必連續注入它:http://stackoverflow.com/questions/14571714/angular-js-make-service - 全球可訪問-從控制器和 - 圖。雖然,不知道它是否仍然符合您的要求? –

回答

0

在我app.js - 引導文件,我現在有這樣的事情:

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