2014-11-25 76 views
2

在JavaScript中定義自定義錯誤的正確方法是什麼?在javascript中創建自定義錯誤的正確方法

通過搜索我發現了大約6種不同的方式來定義自定義錯誤,但我不確定每個人的優點。

與JavaScript中的原型繼承我的(有限)的理解,這個代碼應該是足夠了:

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

這裏有些相關http://stackoverflow.com/questions/783818/how-do-i-create-a-custom-error-in-javascript – 2014-11-25 02:34:29

+0

這是主SO疑問,使我困惑。排名最高的答案列出了自定義錯誤從「Error」對象繼承的兩種不同方式,它們都不使用Object.create()方法。其他答案似乎是這個主題的變化。 – n0w 2014-11-25 02:38:08

+1

'Object.create'只是一個新的方法來做'CustomError.prototype = new Error()' - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create – 2014-11-25 02:42:08

回答

1

我通常只是用throw new Error(...),但對於自定義錯誤我發現下面的代碼工作得很好,仍然給出了喲ü堆在V8的痕跡,即Chrome瀏覽器和node.js中(你不要只是通過調用Error.apply()如其他答案建議):

function CustomError(message) { 
    // Creates the this.stack getter 
    if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor) 
    this.message = message; 
} 
CustomError.prototype = Object.create(Error.prototype); 
CustomError.prototype.constructor = CustomError; 
CustomError.prototype.name = 'CustomError'; 

欲瞭解更多信息,請參閱以下鏈接:

What's a good way to extend Error in JavaScript?

https://plus.google.com/+MalteUbl/posts/HPA9uYimrQg

+0

謝謝。這似乎工作正常,同時也定義'this.stack'可用。我在自己的代碼中做的唯一改變是在構造函數中定義'this.name'。 – n0w 2014-11-25 05:23:17

+0

好的建議;我已經添加了(在原型上做了它,因爲名稱對於所有實例都是一樣的,但它並不重要)。 – 2014-11-26 18:56:26

+0

注意:爲了與IE更全面的兼容性,還需要其他一些東西;請參閱http://stackoverflow.com/a/8460753/560114。 – 2014-11-26 19:00:06

0
function CustomError() { 
    var returned = Error.apply(this, arguments); 
    this.name = "CustomError"; 
    this.message = returned.message; 
} 
CustomError.prototype = Object.create(Error.prototype); 
//CustomError.prototype = new Error(); 

var nie = new CustomError("some message"); 

console.log(nie); 
console.log(nie.name); 
console.log(nie.message); 
3

最簡單的,當然,在我看來,最好用的,除非你需要更多的複雜的錯誤報告/處理是這樣的:

throw Error("ERROR: This is an error, do not be alarmed.") 
相關問題