Don't throw an exception when the argument to %j is an object that
contains circular references, it's not helpful. Catch the exception
and return the string '[Circular]'.
* `%s` - String.
* `%d` - Number (both integer and float).
-* `%j` - JSON.
+* `%j` - JSON. Replaced with the string `'[Circular]'` if the argument
+ contains circular references.
* `%%` - single percent sign (`'%'`). This does not consume an argument.
If the placeholder does not have a corresponding argument, the placeholder is
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
- case '%j': return JSON.stringify(args[i++]);
+ case '%j':
+ try {
+ return JSON.stringify(args[i++]);
+ } catch (_) {
+ return '[Circular]';
+ }
default:
return x;
}
assert.equal(util.format('%s:%s', 'foo', 'bar', 'baz'), 'foo:bar baz');
assert.equal(util.format('%%%s%%', 'hi'), '%hi%');
assert.equal(util.format('%%%s%%%%', 'hi'), '%hi%%');
+
+(function() {
+ var o = {};
+ o.o = o;
+ assert.equal(util.format('%j', o), '[Circular]');
+})();