diff --git a/lib/util.js b/lib/util.js index 2ef7e4e54c5c6d..ac98590464a3fb 100644 --- a/lib/util.js +++ b/lib/util.js @@ -595,9 +595,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 @@ -749,7 +753,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 b80e932dd1c17f..0ea2fd702fd37d 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) {