Permalink
Browse files

Merge pull request #5 from flatiron/toJSON

Error.prototype.toJSON
  • Loading branch information...
2 parents db8ad6f + fea6b74 commit 17acfff11e93ba5d3dcc1a4ca36fa929bc3488ce @indexzero committed Jun 2, 2012
Showing with 67 additions and 1 deletion.
  1. +53 −1 lib/errs.js
  2. +14 −0 test/errs-test.js
View
@@ -15,6 +15,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
// #### @opts {string|object|Array|function} Options for creating the error:
@@ -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); });
@@ -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;
+}
View
@@ -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.