2013-03-30 122 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