Skip to content

Commit 77c69f7

Browse files
DavidCai1111italoacasas
authored andcommitted
lib, test: add duplicate symbol checking in E()
Add duplicate symbol checking in E() to avoid potential confusing result. Increase coverage of internal/errors. PR-URL: #11829 Reviewed-By: James M Snell <[email protected]> Reviewed-By: Colin Ihrig <[email protected]> Reviewed-By: Michaël Zasso <[email protected]> Reviewed-By: Franziska Hinkelmann <[email protected]>
1 parent 7e23072 commit 77c69f7

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

lib/internal/errors.js

+2
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,8 @@ function message(key, args) {
6060
// Utility function for registering the error codes. Only used here. Exported
6161
// *only* to allow for testing.
6262
function E(sym, val) {
63+
const assert = lazyAssert();
64+
assert(messages.has(sym) === false, `Error symbol: ${sym} was already used.`);
6365
messages.set(sym, typeof val === 'function' ? val : String(val));
6466
}
6567

test/parallel/test-internal-errors.js

+12
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ const err1 = new errors.Error('TEST_ERROR_1', 'test');
1212
const err2 = new errors.TypeError('TEST_ERROR_1', 'test');
1313
const err3 = new errors.RangeError('TEST_ERROR_1', 'test');
1414
const err4 = new errors.Error('TEST_ERROR_2', 'abc', 'xyz');
15+
const err5 = new errors.Error('TEST_ERROR_1');
1516

1617
assert(err1 instanceof Error);
1718
assert.strictEqual(err1.name, 'Error[TEST_ERROR_1]');
@@ -33,6 +34,11 @@ assert.strictEqual(err4.name, 'Error[TEST_ERROR_2]');
3334
assert.strictEqual(err4.message, 'abc xyz');
3435
assert.strictEqual(err4.code, 'TEST_ERROR_2');
3536

37+
assert(err5 instanceof Error);
38+
assert.strictEqual(err5.name, 'Error[TEST_ERROR_1]');
39+
assert.strictEqual(err5.message, 'Error for testing purposes: %s');
40+
assert.strictEqual(err5.code, 'TEST_ERROR_1');
41+
3642
assert.throws(
3743
() => new errors.Error('TEST_FOO_KEY'),
3844
/^AssertionError: An invalid error message key was used: TEST_FOO_KEY.$/);
@@ -118,3 +124,9 @@ assert.throws(() => {
118124
type: TypeError,
119125
message: /^Error for testing 2/ }));
120126
}, /AssertionError: .+ does not match \S/);
127+
128+
assert.doesNotThrow(() => errors.E('TEST_ERROR_USED_SYMBOL'));
129+
assert.throws(
130+
() => errors.E('TEST_ERROR_USED_SYMBOL'),
131+
/^AssertionError: Error symbol: TEST_ERROR_USED_SYMBOL was already used\.$/
132+
);

0 commit comments

Comments
 (0)