相关疑难解决方法(0)

什么是在JavaScript中扩展错误的好方法?

我想在我的JS代码中抛出一些东西,我希望它们是instanceof Error,但我也想让它们成为别的东西.

在Python中,通常会有一个子类Exception.

在JS中做什么是合适的?

javascript error-handling exception

340
推荐指数
16
解决办法
11万
查看次数

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

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.做一个对另一个有什么好处吗?

javascript exception-handling exception custom-exceptions

23
推荐指数
1
解决办法
7736
查看次数