在js中捕获自定义异常

use*_*862 2 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!");
   }
}
Run Code Online (Sandbox Code Playgroud)

问题是:如何在catch块中捕获此特定异常?

dav*_*ave 8

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
    }
}
Run Code Online (Sandbox Code Playgroud)