Permalink
Browse files

[api] Add `Error.prototype.toJSON` if it doesnt already exist.

  • Loading branch information...
1 parent db8ad6f commit 1a3116c82a694ee23612fece34daaca360e19ce2 @indexzero committed May 15, 2012
Showing with 41 additions and 0 deletions.
  1. +41 −0 lib/errs.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:
@@ -207,3 +224,27 @@ 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) {
+ Array.prototype.slice.call(arguments, 1).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;
+};

0 comments on commit 1a3116c

Please sign in to comment.