Last active
July 4, 2016 15:30
-
-
Save hashchange/4c1ce239570c77e698c1d2df09d0e540 to your computer and use it in GitHub Desktop.
Patterns for creating custom error types.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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