Skip to content

Commit aa250b8

Browse files
committed
Add support for Error object (yahoo#135)
1 parent f60bab5 commit aa250b8

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -47,13 +47,14 @@ serialize({
4747
fn : function echo(arg) { return arg; },
4848
re : /([^\s]+)/g,
4949
big : BigInt(10),
50+
err : new Error('Error message.'),
5051
});
5152
```
5253

5354
The above will produce the following string output:
5455

5556
```js
56-
'{"str":"string","num":0,"obj":{"foo":"foo"},"arr":[1,2,3],"bool":true,"nil":null,"undef":undefined,"inf":Infinity,"date":new Date("2016-04-28T22:02:17.000Z"),"map":new Map([["hello","world"]]),"set":new Set([123,456]),"fn":function echo(arg) { return arg; },"re":new RegExp("([^\\\\s]+)", "g"),"big":BigInt("10")}'
57+
'{"str":"string","num":0,"obj":{"foo":"foo"},"arr":[1,2,3],"bool":true,"nil":null,"undef":undefined,"inf":Infinity,"date":new Date("2016-04-28T22:02:17.000Z"),"map":new Map([["hello","world"]]),"set":new Set([123,456]),"fn":function echo(arg) { return arg; },"re":new RegExp("([^\\\\s]+)", "g"),"big":BigInt("10"),"err":new Error("Error message.")}'
5758
```
5859

5960
Note: to produced a beautified string, you can pass an optional second argument to `serialize()` to define the number of spaces to be used for the indentation.

index.js

+11-2
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ var randomBytes = require('randombytes');
1111
// Generate an internal UID to make the regexp pattern harder to guess.
1212
var UID_LENGTH = 16;
1313
var UID = generateUID();
14-
var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B|L)-' + UID + '-(\\d+)__@"', 'g');
14+
var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B|L|E)-' + UID + '-(\\d+)__@"', 'g');
1515

1616
var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g;
1717
var IS_PURE_FUNCTION = /function.*?\(/;
@@ -73,6 +73,7 @@ module.exports = function serialize(obj, options) {
7373
var infinities= [];
7474
var bigInts = [];
7575
var urls = [];
76+
var errors = [];
7677

7778
// Returns placeholders for functions and regexps (identified by index)
7879
// which are later replaced by their string representation.
@@ -119,6 +120,10 @@ module.exports = function serialize(obj, options) {
119120
if(origValue instanceof URL) {
120121
return '@__L-' + UID + '-' + (urls.push(origValue) - 1) + '__@';
121122
}
123+
124+
if(origValue instanceof Error) {
125+
return '@__E-' + UID + '-' + (errors.push(origValue) - 1) + '__@';
126+
}
122127
}
123128

124129
if (type === 'function') {
@@ -210,7 +215,7 @@ module.exports = function serialize(obj, options) {
210215
str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
211216
}
212217

213-
if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && arrays.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0 && urls.length === 0) {
218+
if (functions.length === 0 && regexps.length === 0 && dates.length === 0 && maps.length === 0 && sets.length === 0 && arrays.length === 0 && undefs.length === 0 && infinities.length === 0 && bigInts.length === 0 && urls.length === 0 && errors.length === 0) {
214219
return str;
215220
}
216221

@@ -261,6 +266,10 @@ module.exports = function serialize(obj, options) {
261266
return "new URL(\"" + urls[valueIndex].toString() + "\")";
262267
}
263268

269+
if (type === 'E') {
270+
return "new Error(\"" + errors[valueIndex].message + "\")";
271+
}
272+
264273
var fn = functions[valueIndex];
265274

266275
return serializeFunc(fn);

test/unit/serialize.js

+14
Original file line numberDiff line numberDiff line change
@@ -466,6 +466,20 @@ describe('serialize( obj )', function () {
466466
});
467467
});
468468

469+
describe('Error', function () {
470+
it('should serialize Error', function () {
471+
var e = new Error('Error message.')
472+
expect(serialize(e)).to.equal('new Error("Error message.")');
473+
expect(serialize({t: [e]})).to.be.a('string').equal('{"t":[new Error("Error message.")]}');
474+
});
475+
476+
it('should deserialize Error', function () {
477+
var d = eval(serialize(new Error('Error message.')));
478+
expect(d).to.be.a('Error');
479+
expect(d.message).to.equal('Error message.');
480+
});
481+
});
482+
469483
describe('XSS', function () {
470484
it('should encode unsafe HTML chars to Unicode', function () {
471485
expect(serialize('</script>')).to.equal('"\\u003C\\u002Fscript\\u003E"');

0 commit comments

Comments
 (0)