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]'.
This commit is contained in:
parent
7ca77eaf38
commit
2cd7adc7f4
@ -53,7 +53,8 @@ argument. Supported placeholders are:
|
|||||||
|
|
||||||
* `%s` - String.
|
* `%s` - String.
|
||||||
* `%d` - Number (both integer and float).
|
* `%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.
|
* `%%` - single percent sign (`'%'`). This does not consume an argument.
|
||||||
|
|
||||||
If the placeholder does not have a corresponding argument, the placeholder is
|
If the placeholder does not have a corresponding argument, the placeholder is
|
||||||
|
@ -38,7 +38,12 @@ exports.format = function(f) {
|
|||||||
switch (x) {
|
switch (x) {
|
||||||
case '%s': return String(args[i++]);
|
case '%s': return String(args[i++]);
|
||||||
case '%d': return Number(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:
|
default:
|
||||||
return x;
|
return x;
|
||||||
}
|
}
|
||||||
|
@ -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:%s', 'foo', 'bar', 'baz'), 'foo:bar baz');
|
||||||
assert.equal(util.format('%%%s%%', 'hi'), '%hi%');
|
assert.equal(util.format('%%%s%%', 'hi'), '%hi%');
|
||||||
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…
x
Reference in New Issue
Block a user