2013-03-30 120 views
0

我試圖創建一些有用的調試信息自定義異常:檢查自定義異常

var customError = function(name, message) { 

    this.message = message; 
    this.name = name; 

    this.prototype = new Error(); // to make customError "inherit" from the 
            // default error 
}; 

throw new customError('CustomException', 'Something went wrong'); 

但是,所有我得到在控制檯模糊信息:

IE:「 SCRIPT5022:拋出異常,而不是陷入「

火狐: 」未捕獲的異常:[對象的對象]「

爲了從我的例外中獲得有用的信息,我需要更改哪些內容?

回答

1

錯誤使用原型:

var customError = function(name, message) {  
    this.message = message; 
    this.name = name; 
}; 

customError.prototype = new Error(); // to make customError "inherit" from the 
            // default error 

throw new customError('CustomException', 'Something went wrong'); 

prototype是構造(customError)的性質,而不是構造對象(this)的,參見ECMA秒4.2.14.3.5

+0

謝謝。儘管如此,IE仍然給我提供了相同的非言語信息。也許這只是與IE的所有缺點之一:) – Johan

+0

順便說一句,我需要添加'customError.prototype.constructor = customError'或不是必需的嗎? – Johan

+0

@Johan:通常不需要。我相信我曾經看到類似的東西,但我不記得在哪裏。同時,看看http://stackoverflow.com/questions/402538/convention-for-prototype-in​​heritance-in-javascript。它通常是非標準的。 – Zeta