我想在我的JS代码中抛出一些东西,我希望它们是instanceof Error,但我也想让它们成为别的东西.
在Python中,通常会有一个子类Exception.
在JS中做什么是合适的?
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.做一个对另一个有什么好处吗?