Created
September 27, 2012 18:27
-
-
Save mrlannigan/3795558 to your computer and use it in GitHub Desktop.
Error Object Utility
This file contains hidden or 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
/** | |
* Error Object Utility | |
* | |
* The ErrorTypes object defines the arbitrary custom error objects. | |
* | |
* Definitions: | |
* - Each object's key defines the property name in the export | |
* - Each object can have a 'constructor' property that is executed | |
* within the constructor of the Error object | |
* - All other properties of the object are extended onto the prototype | |
*/ | |
var util = require('util'); | |
var ErrorTypes = { | |
CampusError: { | |
name: 'Campus Error', | |
constructor: function(msg, code) { | |
//do nothing, this is here to show example | |
//example usage | |
if (typeof code !== 'undefined' && code !== null) { | |
this.code = code; | |
} | |
} | |
} | |
} | |
/** | |
* Sets up for custom error extension | |
* | |
* @class Abstract Error | |
* @param {String} msg Message | |
* @param {Object} constr Constructor | |
*/ | |
function AbstractError(msg, constr) { | |
Error.captureStackTrace(this, constr || this); | |
this.message = msg || 'Error'; | |
} | |
util.inherits(AbstractError, Error); | |
AbstractError.prototype.name = 'Abstract Error'; | |
// Build error types and export them | |
Object.keys(ErrorTypes).forEach(function(type) { | |
var CustomError = function CustomError(msg) { | |
CustomError.super_.call(this, msg, this.constructor); | |
if (typeof ErrorTypes[type].constructor === 'function') { | |
ErrorTypes[type].constructor.apply(this, arguments); | |
} | |
} | |
util.inherits(CustomError, AbstractError); | |
Object.keys(ErrorTypes[type]).forEach(function(property) { | |
if (property === 'constructor') return; | |
CustomError.prototype[property] = ErrorTypes[type][property]; | |
}); | |
exports[type] = CustomError; | |
}); | |
//if you need this exported | |
//exports.AbstractError = AbstractError; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment