Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Patterns for creating custom error types.
// Pattern for creating a custom error type.
//
// Based on Zakas, Professional Javascript for Web Developers, 3rd Ed., p. 619,
// See also http://stackoverflow.com/a/5251506/508355, including comments.
function MyCustomError ( message ) {
this.message = message;
if ( Error.captureStackTrace ) {
Error.captureStackTrace( this, this.constructor );
} else {
this.stack = ( new Error() ).stack;
}
}
MyCustomError.prototype = Object.create ? Object.create( Error.prototype ) : new Error();
MyCustomError.prototype.name = "MyCustomError";
MyCustomError.prototype.constructor = MyCustomError;
// ------------------------------------------------------------------------
// Generator for custom error types, encapsulating the pattern above.
//
// Based on http://stackoverflow.com/a/27925672/508355
/**
* Creates and returns a custom error type.
*
* @param {string} name of the error type
* @returns {Error}
*/
function createCustomErrorType ( name ) {
function CustomError ( message ) {
this.message = message;
if ( Error.captureStackTrace ) {
Error.captureStackTrace( this, this.constructor );
} else {
this.stack = ( new Error() ).stack;
}
}
CustomError.prototype = new Error();
CustomError.prototype.name = name;
CustomError.prototype.constructor = CustomError;
return CustomError;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment