Last active
August 29, 2015 14:14
-
-
Save feklee/26175c8b81ff19f82a87 to your computer and use it in GitHub Desktop.
Hierarchical error objects in Node.js (example for prototypal inheritance)
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
// 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(); |
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
// 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