在 js 中捕获自定义异常
catching custom exception in js
如果我关注
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 块中捕获这个特定的异常?
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
}
}
如果我关注
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 块中捕获这个特定的异常?
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
}
}