Browse Source

util: don't throw on circular %j input to format()

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]'.
v0.11.5-release
Ben Noordhuis 11 years ago
parent
commit
2cd7adc7f4
  1. 3
      doc/api/util.markdown
  2. 7
      lib/util.js
  3. 6
      test/simple/test-util-format.js

3
doc/api/util.markdown

@ -53,7 +53,8 @@ argument. Supported placeholders are:
* `%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

7
lib/util.js

@ -38,7 +38,12 @@ exports.format = function(f) {
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;
}

6
test/simple/test-util-format.js

@ -60,3 +60,9 @@ assert.equal(util.format('%s:%s', 'foo', 'bar'), 'foo:bar');
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]');
})();

Loading…
Cancel
Save