Skip to content

Commit

Permalink
util: wrap error in brackets without stack
Browse files Browse the repository at this point in the history
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: nodejs#20802
Refs: nodejs#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>
  • Loading branch information
BridgeAR committed May 21, 2018
1 parent 7f0f978 commit afd290d
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 9 deletions.
10 changes: 7 additions & 3 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down
24 changes: 18 additions & 6 deletions test/parallel/test-util-inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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) {
Expand Down

0 comments on commit afd290d

Please sign in to comment.