Skip to content

Instantly share code, notes, and snippets.

@LMnet
Last active December 26, 2015 04:59
Show Gist options
  • Save LMnet/7097132 to your computer and use it in GitHub Desktop.
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.
/**
* 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