catching custom exception in js
Asked Answered
T

1

5

If I have following

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!");
   }
}

Question is: How can I catch this particular exception in catch block?

Thready answered 2/4, 2015 at 20:53 Comment(0)
P
9

JavaScript does not have a standardized way of catching different types of exceptions; however, you can do a general catch and then check the type in the catch. For example:

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
    }
}
Parthenos answered 2/4, 2015 at 21:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.