Today I Learned

hashrocket A Hashrocket project

Custom errors in JavaScript ⚠️

Javascript provides the ability to create custom errors by modifying the prototype of a function to the Error protorype. This is how one would create a custom error:

function ValidationError(message) { = 'ValidationError'; 
  this.message = message; 
ValidationError.prototype = Error.prototype;

throw new ValidationError('the form is invalid');

To catch it you can check the class of an error using instanceof:

try {
	// do stuff
  throw new ValidationError('the form is invalid');
} catch (ex) {
	if (ex instanceof ValidationError) {
  	alert(ex.message); // the form is invalid
  } else {
  	// crash and burn
  	throw ex;
See More #javascript TILs
Looking for help? At Hashrocket, our JavaScript experts launch scalable, performant apps on the Web, Android and iOS. Contact us and find out how we can help you.