From afd290d22475f268010387bec61b8ceb5a51a46b Mon Sep 17 00:00:00 2001 From: Ruben Bridgewater Date: Thu, 17 May 2018 00:45:17 +0200 Subject: [PATCH] util: wrap error in brackets without stack This aligns the visualization of an error with no stack traces set to zero just as it is done in case the error has no stack trace. PR-URL: https://github.com/nodejs/node/pull/20802 Refs: https://github.com/nodejs/node/issues/20253 Reviewed-By: Anna Henningsen Reviewed-By: James M Snell Reviewed-By: Matteo Collina Reviewed-By: Trivikram Kamat --- lib/util.js | 10 +++++++--- test/parallel/test-util-inspect.js | 24 ++++++++++++++++++------ 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/lib/util.js b/lib/util.js index 46ae1724a7c0fb..2c618562170f72 100644 --- a/lib/util.js +++ b/lib/util.js @@ -585,9 +585,13 @@ function formatValue(ctx, value, recurseTimes, ln) { base = `${dateToISOString.call(value)}`; } else if (isError(value)) { // Make error with message first say the error + base = formatError(value); + // Wrap the error in brackets in case it has no stack trace. + if (base.indexOf('\n at') === -1) { + base = `[${base}]`; + } if (keyLength === 0) - return formatError(value); - base = `${formatError(value)}`; + return base; } else if (isAnyArrayBuffer(value)) { // Fast path for ArrayBuffer and SharedArrayBuffer. // Can't do the same for DataView because it has a non-primitive @@ -739,7 +743,7 @@ function formatPrimitive(fn, value, ctx) { } function formatError(value) { - return value.stack || `[${errorToString.call(value)}]`; + return value.stack || errorToString.call(value); } function formatObject(ctx, value, recurseTimes, keys) { diff --git a/test/parallel/test-util-inspect.js b/test/parallel/test-util-inspect.js index b9ed02ddc4a69e..0b31c41b292db4 100644 --- a/test/parallel/test-util-inspect.js +++ b/test/parallel/test-util-inspect.js @@ -496,12 +496,12 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324'); // Exceptions should print the error message, not '{}'. { - const errors = []; - errors.push(new Error()); - errors.push(new Error('FAIL')); - errors.push(new TypeError('FAIL')); - errors.push(new SyntaxError('FAIL')); - errors.forEach((err) => { + [ + new Error(), + new Error('FAIL'), + new TypeError('FAIL'), + new SyntaxError('FAIL') + ].forEach((err) => { assert.strictEqual(util.inspect(err), err.stack); }); try { @@ -515,6 +515,18 @@ assert.strictEqual(util.inspect(-5e-324), '-5e-324'); assert(ex.includes('[message]')); } +{ + const tmp = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + const err = new Error('foo'); + assert.strictEqual(util.inspect(err), '[Error: foo]'); + assert(err.stack); + delete err.stack; + assert(!err.stack); + assert.strictEqual(util.inspect(err), '[Error: foo]'); + Error.stackTraceLimit = tmp; +} + // Doesn't capture stack trace. { function BadCustomError(msg) {