Last active
December 26, 2015 04:59
-
-
Save LMnet/7097132 to your computer and use it in GitHub Desktop.
Gist for creating custom error objects, with inheritance, factory-function and instanceof functionality.
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
/** | |
* Custom Error classes factory | |
* Usage: | |
* var MyError = ErrorFactory('MyError'); | |
* try{ | |
* throw new MyError('my error text'); //or throw MyError('my error text'); | |
* }catch(e){ | |
* if(e instanceof MyError){ | |
* console.log('This is my error!'); | |
* } | |
* } | |
*/ | |
"use strict"; | |
define( | |
['underscore'], | |
function(_){ | |
/** | |
* Function-factory, creates custom Error classes | |
* @param {String} name Name for new class | |
* @return {Error} New Error class | |
*/ | |
return function(name){ | |
if(name === undefined || !_.isString(name)){ | |
throw new Error('You must set class name'); | |
} | |
//constructor | |
function CustomError(message){ | |
//for using without new statement | |
if(this === undefined){ | |
return new CustomError(message); | |
} | |
this.name = name; | |
this.message = message || ''; | |
} | |
//inheritance | |
CustomError.prototype = new Error(); | |
CustomError.prototype.constructor = CustomError; | |
return CustomError; | |
} | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment