Skip to content

Commit

Permalink
errors: use lazy assert to avoid issues on startup
Browse files Browse the repository at this point in the history
Use of assert must be lazy to allow errors to be used early
before the process is completely set up
  • Loading branch information
jasnell committed Apr 27, 2017
1 parent 4271254 commit 896e8db
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 8 deletions.
11 changes: 9 additions & 2 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
// value statically and permanently identifies the error. While the error
// message may change, the code should not.

const assert = require('assert');
const kCode = Symbol('code');
const messages = new Map();

Expand All @@ -17,6 +16,13 @@ function lazyUtil() {
return util;
}

var assert;
function lazyAssert() {
if (!assert)
assert = require('assert');
return assert;
}

function makeNodeError(Base) {
return class NodeError extends Base {
constructor(key, ...args) {
Expand All @@ -36,6 +42,7 @@ function makeNodeError(Base) {
}

function message(key, args) {
const assert = lazyAssert();
assert.strictEqual(typeof key, 'string');
const util = lazyUtil();
const msg = messages.get(key);
Expand All @@ -54,7 +61,6 @@ function message(key, args) {
// Utility function for registering the error codes. Only used here. Exported
// *only* to allow for testing.
function E(sym, val) {
assert(messages.has(sym) === false, `Error symbol: ${sym} was already used.`);
messages.set(sym, typeof val === 'function' ? val : String(val));
}

Expand Down Expand Up @@ -99,6 +105,7 @@ E('ERR_UNKNOWN_BUILTIN_MODULE', (id) => `No such built-in module: ${id}`);
// Add new errors from here...

function invalidArgType(name, expected, actual) {
const assert = lazyAssert();
assert(name, 'name is required');
var msg = `The "${name}" argument must be ${oneOf(expected, 'type')}`;
if (arguments.length >= 3) {
Expand Down
6 changes: 0 additions & 6 deletions test/parallel/test-internal-errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,12 +125,6 @@ assert.throws(() => {
message: /^Error for testing 2/ }));
}, /AssertionError: .+ does not match \S/);

assert.doesNotThrow(() => errors.E('TEST_ERROR_USED_SYMBOL'));
assert.throws(
() => errors.E('TEST_ERROR_USED_SYMBOL'),
/^AssertionError: Error symbol: TEST_ERROR_USED_SYMBOL was already used\.$/
);

// // Test ERR_INVALID_ARG_TYPE
assert.strictEqual(errors.message('ERR_INVALID_ARG_TYPE', ['a', 'b']),
'The "a" argument must be of type b');
Expand Down

0 comments on commit 896e8db

Please sign in to comment.