Skip to content

Instantly share code, notes, and snippets.

@feklee
Last active August 29, 2015 14:14
Show Gist options
  • Save feklee/26175c8b81ff19f82a87 to your computer and use it in GitHub Desktop.
Save feklee/26175c8b81ff19f82a87 to your computer and use it in GitHub Desktop.
Hierarchical error objects in Node.js (example for prototypal inheritance)
// Tested with Node.js v0.10.35.
/*jslint node: true, maxerr: 50, maxlen: 80 */
'use strict';
var customErrors = require('./custom_errors'), test;
test = function () {
console.log(customErrors.isbnError);
console.log(customErrors.isbnError.withMessage('Just a test!'));
console.log(customErrors.invalidArgumentError.isPrototypeOf(
customErrors.isbnError
));
console.log(customErrors.invalidArgumentError.isPrototypeOf(
customErrors.germanIsbnError
));
console.log(customErrors.isbnError.isPrototypeOf(
customErrors.germanIsbnError
));
console.log(customErrors.isbnError.isPrototypeOf(
customErrors.permissionError
));
};
test();
// Creates a tree of error objects.
/*jslint node: true, maxerr: 50, maxlen: 80 */
'use strict';
var customError = new Error(), createError, exportError;
createError = function (name, proto) {
var error = Object.create(proto || customError, {
name: {value: name},
withMessage: {value: function (message) {
error.message = message;
return error;
}}
});
return error;
};
exportError = function (name, nameOfProto) {
var proto = module.exports[nameOfProto],
error = createError(name, proto);
Object.defineProperty(module.exports, name, {
get: function get() {
name.message = '';
Error.captureStackTrace(error, get);
return error;
}
});
};
exportError('invalidArgumentError');
exportError('isbnError', 'invalidArgumentError');
exportError('germanIsbnError', 'isbnError');
exportError('permissionError');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment