Skip to content

Instantly share code, notes, and snippets.

@mbrowne
Last active December 28, 2016 02:06
Show Gist options
  • Save mbrowne/fe45db61cea7858d11be933a998926a8 to your computer and use it in GitHub Desktop.
Save mbrowne/fe45db61cea7858d11be933a998926a8 to your computer and use it in GitHub Desktop.
Subclass error in JS with native-like console output
function CustomError(message) {
if (!(this instanceof CustomError)) {
throw new TypeError("Constructor 'CustomError' cannot be invoked without 'new'");
}
var err;
if (Object.setPrototypeOf) {
err = new Error(message);
Object.setPrototypeOf(err, CustomError.prototype);
}
else {
err = this;
}
if (Error.captureStackTrace) {
Error.captureStackTrace(err, CustomError);
}
return err;
}
CustomError.prototype = Object.create(Error.prototype);
CustomError.prototype.name = 'CustomError';
@mbrowne
Copy link
Author

mbrowne commented Dec 28, 2016

Note: One possible downside of this approach is that errors appear in the console as Error: ... rather than CustomError: .... But otherwise they appear just the same as errors extended using ES6 classes (class CustomError extends Error {}).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment