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

Viv*_*ath 23 javascript exception-handling exception custom-exceptions

Douglas Crockford建议做这样的事情:

throw {
    name: "System Error",
    message: "Something horrible happened."
};
Run Code Online (Sandbox Code Playgroud)

但你也可以这样做:

function IllegalArgumentException(message) {
    this.message = message;
}

throw new IllegalArgumentException("Argument cannot be less than zero");
Run Code Online (Sandbox Code Playgroud)

然后做:

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

我想你可以type在Crockford的实现中包含一个属性,然后检查它而不是做一个instanceof.做一个对另一个有什么好处吗?

ren*_*ene 25

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

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