Skip to content

Commit

Permalink
util: throw toJSON errors when formatting %j
Browse files Browse the repository at this point in the history
Previously all errors resulting from JSON.stringify were treated as a
proof for circularity of the object structure. That is not the case if
the `toJSON` method of the object throws an error. Explicitly check for
the exact error message when determining the object structure's
cyclicity.

PR-URL: #11708
Reviewed-By: Luigi Pinca <luigipinca@gmail.com>
Reviewed-By: Anna Henningsen <anna@addaleax.net>
Reviewed-By: Sakthipriyan Vairamani <thechargingvolcano@gmail.com>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
  • Loading branch information
TimothyGu committed Mar 11, 2017
1 parent 98e54b0 commit 455e6f1
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
8 changes: 6 additions & 2 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,17 @@ const inspectDefaultOptions = Object.seal({
breakLength: 60
});

const CIRCULAR_ERROR_MESSAGE = 'Converting circular structure to JSON';

var Debug;

function tryStringify(arg) {
try {
return JSON.stringify(arg);
} catch (_) {
return '[Circular]';
} catch (err) {
if (err.name === 'TypeError' && err.message === CIRCULAR_ERROR_MESSAGE)
return '[Circular]';
throw err;
}
}

Expand Down
10 changes: 10 additions & 0 deletions test/parallel/test-util-format.js
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ assert.strictEqual(util.format('o: %j, a: %j'), 'o: %j, a: %j');
assert.strictEqual(util.format('%j', o), '[Circular]');
}

{
const o = {
toJSON() {
throw new Error('Not a circular object but still not serializable');
}
};
assert.throws(() => util.format('%j', o),
/^Error: Not a circular object but still not serializable$/);
}

// Errors
const err = new Error('foo');
assert.strictEqual(util.format(err), err.stack);
Expand Down

0 comments on commit 455e6f1

Please sign in to comment.