Skip to content

Commit

Permalink
Merge pull request #5 from flatiron/toJSON
Browse files Browse the repository at this point in the history
Error.prototype.toJSON
  • Loading branch information
indexzero committed Jun 2, 2012
2 parents db8ad6f + fea6b74 commit 17acfff
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 1 deletion.
54 changes: 53 additions & 1 deletion lib/errs.js
Expand Up @@ -14,6 +14,23 @@ var events = require('events'),
//
exports.registered = {};

//
// Add `Error.prototype.toJSON` if it doesn't exist.
//
if (!Error.prototype.toJSON) {
Object.defineProperty(Error.prototype, 'toJSON', {
enumerable: false,
value: function () {
return mixin({
message: this.message,
stack: this.stack,
arguments: this.arguments,
type: this.type
}, this);
}
});
}

//
// ### function create (type, opts)
// #### @type {string} **Optional** Registered error type to create
Expand Down Expand Up @@ -173,7 +190,7 @@ exports.handle = function (error, callback, stream) {
if (typeof callback === 'function') {
callback(error);
}

if (typeof callback !== 'function' || stream) {
var emitter = stream || callback || new events.EventEmitter();
process.nextTick(function () { emitter.emit('error', error); });
Expand Down Expand Up @@ -207,3 +224,38 @@ exports.register = function (type, proto) {
exports.unregister = function (type) {
delete exports.registered[type];
};

//
// ### function mixin (target [source0, source1, ...])
// Copies enumerable properties from `source0 ... sourceN`
// onto `target` and returns the resulting object.
//
function mixin(target) {
//
// Quickly and performantly (in V8) `Arrayify` arguments.
//
var len = arguments.length,
args = new Array(len - 1),
i = 1;

for (; i < len; i++) {
args[i - 1] = arguments[i];
}

args.forEach(function (o) {
Object.keys(o).forEach(function (attr) {
var getter = o.__lookupGetter__(attr),
setter = o.__lookupSetter__(attr);

if (!getter && !setter) {
target[attr] = o[attr];
}
else {
if (setter) { target.__defineSetter__(attr, setter) }
if (getter) { target.__defineGetter__(attr, getter) }
}
});
});

return target;
}
14 changes: 14 additions & 0 deletions test/errs-test.js
Expand Up @@ -146,4 +146,18 @@ vows.describe('errs').addBatch({
}
}
}
}).addBatch({
"Using errs module": {
"Error.prototype.toJSON": {
"should exist": function () {
assert.isFunction(Error.prototype.toJSON);

var json = (new Error('Testing 12345')).toJSON();

['message', 'stack', 'arguments', 'type'].forEach(function (prop) {
assert.isObject(Object.getOwnPropertyDescriptor(json, prop));
})
}
}
}
}).export(module);

0 comments on commit 17acfff

Please sign in to comment.