Skip to content

Commit 455e6f1

Browse files
committed
util: throw toJSON errors when formatting %j
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 <[email protected]> Reviewed-By: Anna Henningsen <[email protected]> Reviewed-By: Sakthipriyan Vairamani <[email protected]> Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: Colin Ihrig <[email protected]>
1 parent 98e54b0 commit 455e6f1

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

lib/util.js

+6-2
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,17 @@ const inspectDefaultOptions = Object.seal({
3838
breakLength: 60
3939
});
4040

41+
const CIRCULAR_ERROR_MESSAGE = 'Converting circular structure to JSON';
42+
4143
var Debug;
4244

4345
function tryStringify(arg) {
4446
try {
4547
return JSON.stringify(arg);
46-
} catch (_) {
47-
return '[Circular]';
48+
} catch (err) {
49+
if (err.name === 'TypeError' && err.message === CIRCULAR_ERROR_MESSAGE)
50+
return '[Circular]';
51+
throw err;
4852
}
4953
}
5054

test/parallel/test-util-format.js

+10
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,16 @@ assert.strictEqual(util.format('o: %j, a: %j'), 'o: %j, a: %j');
8686
assert.strictEqual(util.format('%j', o), '[Circular]');
8787
}
8888

89+
{
90+
const o = {
91+
toJSON() {
92+
throw new Error('Not a circular object but still not serializable');
93+
}
94+
};
95+
assert.throws(() => util.format('%j', o),
96+
/^Error: Not a circular object but still not serializable$/);
97+
}
98+
8999
// Errors
90100
const err = new Error('foo');
91101
assert.strictEqual(util.format(err), err.stack);

0 commit comments

Comments
 (0)