Custom errors in JavaScript ⚠️

April 27, 2018|
1 min read
  • 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;
  }
}

© 2023, Dorian Karter