在JavaScript中捕获自定义异常

5
如果我有以下内容:
function ValidationException(nr, msg){
   this.message = msg;
   this.name = "my exception";
   this.number = nr;
}
function myFunction(dayOfWeek){
   if(dayOfWeek > 7){
      throw new ValidationException(dayOfWeek, "7days only!");
   }
}

问题是: 如何在catch块中捕获这个特定的异常?
1个回答

9

JavaScript 没有标准化的捕获不同类型异常的方法;但是,您可以使用通用的catch,然后在catch中检查类型。例如:

try {
    myFunction();
} catch (e) {
    if (e instanceof ValidationException) {
        // statements to handle ValidationException exceptions
    } else {
       // statements to handle any unspecified exceptions
       console.log(e); //generic error handling goes here
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接