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 <anna@addaleax.net>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
Reviewed-By: Trivikram Kamat <trivikr.dev@gmail.com>
This commit is contained in:
Ruben Bridgewater 2018-05-17 00:45:17 +02:00
parent 7f0f978aff
commit afd290d224
No known key found for this signature in database
GPG Key ID: F07496B3EB3C1762
2 changed files with 25 additions and 9 deletions

View File

@ -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) {

View File

@ -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) {