在JavaScript中抛出自定义异常。要使用哪种风格? [英] Throwing custom exceptions in Javascript. Which style to use?
问题描述
throw {
name:System Error,
消息:有可怕的事发生了。
};
但你也可以这样做:
函数IllegalArgumentException(message){
this.message = message;
}
抛出新的IllegalArgumentException(参数不能小于零);
然后执行:
try {
//一些生成异常的代码
} catch(e){
if(e instanceof IllegalArgumentException){
//处理这个
} else if(e instanceof SomeOtherTypeOfException){
//处理这个
}
}
我想您可以在Crockford的实现中包含一个类型
属性,然后检查,而不是执行 instanceof
。
请注意,与此同时,大多数JavaScript环境都提供了错误对象作为异常的基础。它已经允许您定义消息,但也提供了一个有用的堆栈属性来跟踪异常的上下文。
您可以通过使用原型继承来创建自己的异常类型。已经有几个stackoverflow讨论(例如:这里),如何正确地做到这一点。不过,我不得不挖一点点,直到找到正确和现代的方法。请注意,Mozilla文档(见上文)中提出的方法不受stackoverflow社区的喜爱。经过大量的阅读后,我出现了从Error.prototype继承的方法:
函数IllegalArgumentException(sMessage){
this.name =IllegalArgumentException;
this.message = sMessage;
this.stack =(new Error())。
}
IllegalArgumentException.prototype = Object.create(Error.prototype);
IllegalArgumentException.prototype.constructor = IllegalArgumentException;
Douglas Crockford recommends doing something like this:
throw {
name: "System Error",
message: "Something horrible happened."
};
But you could also do something like this:
function IllegalArgumentException(message) {
this.message = message;
}
throw new IllegalArgumentException("Argument cannot be less than zero");
and then do:
try {
//some code that generates exceptions
} catch(e) {
if(e instanceof IllegalArgumentException) {
//handle this
} else if(e instanceof SomeOtherTypeOfException) {
//handle this
}
}
I guess you could include a type
property in Crockford's implementation and then examine that instead of doing an instanceof
. Is there any advantage from doing one versus the other?
Please note that meanwhile most of the JavaScripts environments provide the Error object as basis for exceptions. It already allows you to define a message, but also provides a useful stack property to track down the context of the exception. You can create your own exception type by using prototypical inheritance. There are already several stackoverflow discussions (for example: here), how to do this properly. However, I had to dig a little bit until I found the correct and modern approach. Please be aware that the approach that is suggested in the Mozilla documentation (see above) is not liked by the stackoverflow community. After a lot of reading I came out with that approach for inherit from 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;
这篇关于在JavaScript中抛出自定义异常。要使用哪种风格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!