检查自定义异常

时间:2013-03-30 22:00:47

标签: javascript exception

我正在尝试使用一些有用的调试信息创建自定义异常:

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:异常抛出而未被抓住”

Firefox :“未捕获的异常:[object Object]”

为了从我的异常中获得有用的东西,我需要更改什么?

1 个答案:

答案 0 :(得分: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 sec 4.2.14.3.5