Search code examples
javascriptexceptiontry-catchthrowcustom-exceptions

catching custom exception in js


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?


Solution

  • 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
        }
    }