Custom errors in JavaScript ⚠️

April 27, 2018

  • javascript

Originally posted by me on Hashrocket TIL

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) { 
  this.name = 'ValidationError'; 
  this.message = message; 
}
ValidationError.prototype = Error.prototype;

// USAGE
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;
  }
}

Written by Dorian Karter, a Sr. Software Engineer
Github | Twitter

© 2021, Dorian Karter