在js中捕获自定义异常

时间:2015-04-02 20:53:38

标签: javascript exception-handling try-catch throw custom-exceptions

如果我有以下

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 个答案:

答案 0 :(得分:7)

JavaScript does not have a standardized捕获不同类型异常的方法;但是,您可以执行常规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
    }
}
相关问题