Skip to content

Commit 2e8217c

Browse files
committed
assert: improve AssertionError in case of "Errors"
Showing the stack trace in a error message obfuscates the actual message and should not be visible therefore. PR-URL: #15025 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Joyee Cheung <[email protected]>
1 parent dcb24e3 commit 2e8217c

File tree

2 files changed

+23
-9
lines changed

2 files changed

+23
-9
lines changed

lib/internal/errors.js

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,21 +36,26 @@ class AssertionError extends Error {
3636
if (typeof options !== 'object' || options === null) {
3737
throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
3838
}
39-
if (options.message) {
40-
super(options.message);
39+
var { actual, expected, message, operator, stackStartFunction } = options;
40+
if (message) {
41+
super(message);
4142
} else {
43+
if (actual && actual.stack && actual instanceof Error)
44+
actual = `${actual.name}: ${actual.message}`;
45+
if (expected && expected.stack && expected instanceof Error)
46+
expected = `${expected.name}: ${expected.message}`;
4247
if (util === null) util = require('util');
43-
super(`${util.inspect(options.actual).slice(0, 128)} ` +
44-
`${options.operator} ${util.inspect(options.expected).slice(0, 128)}`);
48+
super(`${util.inspect(actual).slice(0, 128)} ` +
49+
`${operator} ${util.inspect(expected).slice(0, 128)}`);
4550
}
4651

47-
this.generatedMessage = !options.message;
52+
this.generatedMessage = !message;
4853
this.name = 'AssertionError [ERR_ASSERTION]';
4954
this.code = 'ERR_ASSERTION';
50-
this.actual = options.actual;
51-
this.expected = options.expected;
52-
this.operator = options.operator;
53-
Error.captureStackTrace(this, options.stackStartFunction);
55+
this.actual = actual;
56+
this.expected = expected;
57+
this.operator = operator;
58+
Error.captureStackTrace(this, stackStartFunction);
5459
}
5560
}
5661

test/parallel/test-assert.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -743,3 +743,12 @@ assert.throws(() => {
743743
}));
744744
});
745745
}
746+
747+
common.expectsError(
748+
() => assert.strictEqual(new Error('foo'), new Error('foobar')),
749+
{
750+
code: 'ERR_ASSERTION',
751+
type: assert.AssertionError,
752+
message: /^'Error: foo' === 'Error: foobar'$/
753+
}
754+
);

0 commit comments

Comments
 (0)