在决定是否忽略时,处理Try Catch
结构中的重新抛出错误,唯一确定错误的最佳方法是什么?
我找不到任何标准错误编号,是否必须解析name
和message
属性?
编辑:在下面的示例中,我想检查错误是否是由于listEvent上缺少属性,其关键是evnt.type的值。如果这是错误的来源,我想忽略它,否则我想重新抛出它让它冒出来。
我能想到的唯一方法是点击这样的错误......
try{
listEvent[evnt.type](procedure)
}catch(error){
if (error.message.match(evnt.type)) {
console.log(error.name + ' ' + error.message + ' - ignored')
} else {
throw error
}
}
答案 0 :(得分:1)
创建自定义例外,然后使用instanceof
:
function IllegalArgumentException(message) {
this.message = message;
}
您还希望扩展Error
原型:
IllegalArgumentException.prototype = new Error();
IllegalArgumentException.prototype.constructor = Error;
然后您可以这样使用:
throw new IllegalArgumentException("Argument cannot be less than zero");
然后,您可以使用instanceof
检查类型:
try {
// Some code that generates exceptions
} catch (e) {
if (e instanceof IllegalArgumentException) {
// Handle this
} else if (e instanceof SomeOtherTypeOfException) {
// Handle this
}
}
您还可以将任何其他属性添加到异常的构造函数中。
就你的例子而言,我不确定你要做什么。如果listEvent[evnt.type]
不是undefined
中的属性或密钥,event.type
将返回listEvent
。通过这样做,最好看看evnt.type
是否存在:
if (typeof listEvent[evnt.type] !== "undefined") {
listEvent[evnt.type](procedure);
}