在Javascript中抛出自定义异常。使用哪种样式?

在Javascript中抛出自定义异常。使用哪种样式?,javascript,exception,exception-handling,custom-exceptions,Javascript,Exception,Exception Handling,Custom Exceptions,Douglas Crockford建议您这样做: throw { name: "System Error", message: "Something horrible happened." }; function IllegalArgumentException(message) { this.message = message; } throw new IllegalArgumentException("Argument cannot be less than ze

Douglas Crockford建议您这样做:

throw {
    name: "System Error",
    message: "Something horrible happened."
};
function IllegalArgumentException(message) {
    this.message = message;
}

throw new IllegalArgumentException("Argument cannot be less than zero");
但你也可以这样做:

throw {
    name: "System Error",
    message: "Something horrible happened."
};
function IllegalArgumentException(message) {
    this.message = message;
}

throw new IllegalArgumentException("Argument cannot be less than zero");
然后做:

try {
    //some code that generates exceptions
} catch(e) {    
    if(e instanceof IllegalArgumentException) {
        //handle this
    } else if(e instanceof SomeOtherTypeOfException) {
        //handle this
    }
}

我想您可以在Crockford的实现中包含一个
类型
属性,然后检查它,而不是执行
实例。做一个和另一个相比有什么好处吗?

我赞成第二个,因为它在代码纯度方面更易于重用。确切地说,如果我要在几个地方抛出相同的异常(甚至是具有不同消息的相同异常类型),那么第一种方法会使我的代码变得混乱(巨大)。

请注意,同时,大多数JavaScripts环境为异常提供了as基础。它已经允许您定义消息,但也提供了有用的堆栈属性来跟踪异常的上下文。 您可以使用原型继承创建自己的异常类型。已经有几个stackoverflow讨论(例如:),如何正确执行此操作。然而,我不得不挖掘一点,直到我找到正确和现代的方法。请注意,stackoverflow社区不喜欢Mozilla文档(见上文)中建议的方法。经过大量阅读,我提出了从错误继承的方法。原型:

function IllegalArgumentException(sMessage) {
    this.name = "IllegalArgumentException";
    this.message = sMessage;
    this.stack = (new Error()).stack;
}
IllegalArgumentException.prototype = Object.create(Error.prototype);
IllegalArgumentException.prototype.constructor = IllegalArgumentException;

对于习惯于Java风格异常的人来说,第二种形式看起来更。。。更熟悉。是的,正是因为这个原因,我偏爱第二种我赞成第二种方法,因为它在代码纯度方面更易于重用。确切地说,如果我要在几个地方抛出相同的异常类型,那么第一种方法会使我的代码变得凌乱(巨大)。我喜欢它提供的封装优势。事实上,我在几个地方抛出了异常,第一种方法开始变得笨拙。如果你把它作为答案贴出来,我可以接受。