//Testing custom Exceptions - see below: $('#submitForm').submit(function(event) { try { myFunction($('#dayOfWeek').val()); } catch(e) { if(e instanceof ValidationException) { alert('ValidationException: ' + e.message); } else if(e instanceof LogicException) { alert('LogicException: ' + e.message); } else { alert('Other exception: ' + e.message); } /* On the other hand, this does not work(code above is valid): switch(e) { case ValidationException: alert('ValidationException: ' + e.message); break; case LogicException: alert('LogicException: ' + e.message); break; default: alert('Other exception: ' + e.message); break; } */ } event.preventDefault(); }); //Define a custom exception that we would like to throw under the right conditions: function ValidationException(number, exception) { this.message = exception; this.name = "myLibrary Validation Exception"; this.number = number; this.type = "ValidationException"; } //Possible to let our error message inherit from the general Error object: //ValidationException.protoType = Error.protoType; function LogicExcpetion(number, message) { this.message = message; this.name = "myLibrary Logic Exception"; this.number = number; this.type = "LogicExpetion"; } function myFunction(dayOfWeek) { if(dayOfWeek > 7) { throw new ValidationException(123, "dayOfWeek must be 7 ot less"); } }
<form id="submitForm" action="demo_form_action.asp" method="post"> <b>Email:</b> <input type="text" id="dayOfWeek" value="12" /><br/> <input type="submit" /> </form>