From 1e8d110e640c658e4f6ed7540db62d063269ba6c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C3=ABl=20Zasso?= Date: Tue, 27 Feb 2018 14:55:32 +0100 Subject: [PATCH] lib: port errors to new system This is a first batch of updates that touches non-underscored modules in lib. PR-URL: https://github.com/nodejs/node/pull/19034 Reviewed-By: James M Snell Reviewed-By: Ruben Bridgewater Reviewed-By: Joyee Cheung --- lib/assert.js | 21 ++-- lib/async_hooks.js | 22 ++-- lib/buffer.js | 109 ++++++++---------- lib/child_process.js | 103 +++++++---------- lib/crypto.js | 9 +- lib/dgram.js | 67 ++++++----- lib/dns.js | 40 ++++--- lib/domain.js | 13 ++- lib/events.js | 24 ++-- lib/fs.js | 62 ++++------ lib/https.js | 4 +- lib/inspector.js | 25 ++-- lib/module.js | 14 ++- lib/net.js | 55 ++++----- lib/path.js | 14 +-- lib/perf_hooks.js | 17 ++- lib/querystring.js | 4 +- lib/readline.js | 23 ++-- lib/repl.js | 18 +-- lib/string_decoder.js | 11 +- lib/timers.js | 8 +- lib/tls.js | 4 +- lib/tty.js | 5 +- lib/url.js | 10 +- lib/util.js | 31 +++-- lib/v8.js | 4 +- lib/vm.js | 11 +- lib/zlib.js | 45 ++++---- ...ild-process-spawnsync-validation-errors.js | 18 ++- test/parallel/test-module-loading-error.js | 2 +- .../test-net-server-listen-options.js | 2 +- 31 files changed, 377 insertions(+), 418 deletions(-) diff --git a/lib/assert.js b/lib/assert.js index 67c658d9e68bb3..7d894518b107d2 100644 --- a/lib/assert.js +++ b/lib/assert.js @@ -25,7 +25,13 @@ const { isDeepEqual, isDeepStrictEqual } = require('internal/util/comparisons'); -const { AssertionError, TypeError, errorCache } = require('internal/errors'); +const { + AssertionError, + errorCache, + codes: { + ERR_INVALID_ARG_TYPE + } +} = require('internal/errors'); const { openSync, closeSync, readSync } = require('fs'); const { parseExpressionAt } = require('internal/deps/acorn/dist/acorn'); const { inspect } = require('util'); @@ -380,8 +386,9 @@ function expectedException(actual, expected, msg) { return expected.test(actual); // assert.doesNotThrow does not accept objects. if (arguments.length === 2) { - throw new TypeError('ERR_INVALID_ARG_TYPE', 'expected', - ['Function', 'RegExp'], expected); + throw new ERR_INVALID_ARG_TYPE( + 'expected', ['Function', 'RegExp'], expected + ); } // The name and message could be non enumerable. Therefore test them // explicitly. @@ -408,8 +415,7 @@ function expectedException(actual, expected, msg) { function getActual(block) { if (typeof block !== 'function') { - throw new TypeError('ERR_INVALID_ARG_TYPE', 'block', 'Function', - block); + throw new ERR_INVALID_ARG_TYPE('block', 'Function', block); } try { block(); @@ -425,10 +431,7 @@ assert.throws = function throws(block, error, message) { if (typeof error === 'string') { if (arguments.length === 3) - throw new TypeError('ERR_INVALID_ARG_TYPE', - 'error', - ['Function', 'RegExp'], - error); + throw new ERR_INVALID_ARG_TYPE('error', ['Function', 'RegExp'], error); message = error; error = null; diff --git a/lib/async_hooks.js b/lib/async_hooks.js index ae8dc939ce26ee..0c425e694584eb 100644 --- a/lib/async_hooks.js +++ b/lib/async_hooks.js @@ -1,6 +1,10 @@ 'use strict'; -const errors = require('internal/errors'); +const { + ERR_ASYNC_CALLBACK, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_ASYNC_ID +} = require('internal/errors').codes; const async_wrap = process.binding('async_wrap'); const internal_async_hooks = require('internal/async_hooks'); @@ -41,15 +45,15 @@ const { class AsyncHook { constructor({ init, before, after, destroy, promiseResolve }) { if (init !== undefined && typeof init !== 'function') - throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'hook.init'); + throw new ERR_ASYNC_CALLBACK('hook.init'); if (before !== undefined && typeof before !== 'function') - throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'hook.before'); + throw new ERR_ASYNC_CALLBACK('hook.before'); if (after !== undefined && typeof after !== 'function') - throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'hook.after'); + throw new ERR_ASYNC_CALLBACK('hook.after'); if (destroy !== undefined && typeof destroy !== 'function') - throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'hook.destroy'); + throw new ERR_ASYNC_CALLBACK('hook.destroy'); if (promiseResolve !== undefined && typeof promiseResolve !== 'function') - throw new errors.TypeError('ERR_ASYNC_CALLBACK', 'hook.promiseResolve'); + throw new ERR_ASYNC_CALLBACK('hook.promiseResolve'); this[init_symbol] = init; this[before_symbol] = before; @@ -140,7 +144,7 @@ function showEmitBeforeAfterWarning() { class AsyncResource { constructor(type, opts = {}) { if (typeof type !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'type', 'string'); + throw new ERR_INVALID_ARG_TYPE('type', 'string'); if (typeof opts === 'number') { opts = { triggerAsyncId: opts, requireManualDestroy: false }; @@ -152,9 +156,7 @@ class AsyncResource { // triggerAsyncId. const triggerAsyncId = opts.triggerAsyncId; if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) { - throw new errors.RangeError('ERR_INVALID_ASYNC_ID', - 'triggerAsyncId', - triggerAsyncId); + throw new ERR_INVALID_ASYNC_ID('triggerAsyncId', triggerAsyncId); } this[async_id_symbol] = newAsyncId(); diff --git a/lib/buffer.js b/lib/buffer.js index add3303824b687..fc42f771c24033 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -57,7 +57,16 @@ const { const { pendingDeprecation } = process.binding('config'); -const errors = require('internal/errors'); +const { + ERR_BUFFER_OUT_OF_BOUNDS, + ERR_INDEX_OUT_OF_RANGE, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE, + ERR_INVALID_BUFFER_SIZE, + ERR_INVALID_OPT_VALUE, + ERR_NO_LONGER_SUPPORTED, + ERR_UNKNOWN_ENCODING +} = require('internal/errors').codes; const internalBuffer = require('internal/buffer'); @@ -166,9 +175,7 @@ function Buffer(arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'string', 'string', arg - ); + throw new ERR_INVALID_ARG_TYPE('string', 'string', arg); } return Buffer.alloc(arg); } @@ -197,8 +204,7 @@ Buffer.from = function from(value, encodingOrOffset, length) { return fromArrayBuffer(value, encodingOrOffset, length); if (value === null || value === undefined) { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', + throw new ERR_INVALID_ARG_TYPE( 'first argument', ['string', 'Buffer', 'ArrayBuffer', 'Array', 'Array-like Object'], value @@ -206,9 +212,7 @@ Buffer.from = function from(value, encodingOrOffset, length) { } if (typeof value === 'number') { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'value', 'not number', value - ); + throw new ERR_INVALID_ARG_TYPE('value', 'not number', value); } const valueOf = value.valueOf && value.valueOf(); @@ -225,8 +229,7 @@ Buffer.from = function from(value, encodingOrOffset, length) { length); } - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', + throw new ERR_INVALID_ARG_TYPE( 'first argument', ['string', 'Buffer', 'ArrayBuffer', 'Array', 'Array-like Object'], value @@ -242,9 +245,9 @@ function assertSize(size) { let err = null; if (typeof size !== 'number') { - err = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'size', 'number', size); + err = new ERR_INVALID_ARG_TYPE('size', 'number', size); } else if (size < 0 || size > kMaxLength) { - err = new errors.RangeError('ERR_INVALID_OPT_VALUE', 'size', size); + err = new ERR_INVALID_OPT_VALUE.RangeError('size', size); } if (err !== null) { @@ -323,7 +326,7 @@ function fromString(string, encoding) { } else { length = byteLength(string, encoding, true); if (length === -1) - throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding); + throw new ERR_UNKNOWN_ENCODING(encoding); if (string.length === 0) return new FastBuffer(); } @@ -365,7 +368,7 @@ function fromArrayBuffer(obj, byteOffset, length) { const maxLength = obj.byteLength - byteOffset; if (maxLength < 0) - throw new errors.RangeError('ERR_BUFFER_OUT_OF_BOUNDS', 'offset'); + throw new ERR_BUFFER_OUT_OF_BOUNDS('offset'); if (length === undefined) { length = maxLength; @@ -374,7 +377,7 @@ function fromArrayBuffer(obj, byteOffset, length) { length = +length; if (length > 0) { if (length > maxLength) - throw new errors.RangeError('ERR_BUFFER_OUT_OF_BOUNDS', 'length'); + throw new ERR_BUFFER_OUT_OF_BOUNDS('length'); } else { length = 0; } @@ -414,9 +417,7 @@ Buffer.isBuffer = function isBuffer(b) { Buffer.compare = function compare(a, b) { if (!isUint8Array(a) || !isUint8Array(b)) { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', ['buf1', 'buf2'], ['Buffer', 'Uint8Array'] - ); + throw new ERR_INVALID_ARG_TYPE(['buf1', 'buf2'], ['Buffer', 'Uint8Array']); } if (a === b) { @@ -435,9 +436,7 @@ Buffer[kIsEncodingSymbol] = Buffer.isEncoding; Buffer.concat = function concat(list, length) { var i; if (!Array.isArray(list)) { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'list', ['Array', 'Buffer', 'Uint8Array'] - ); + throw new ERR_INVALID_ARG_TYPE('list', ['Array', 'Buffer', 'Uint8Array']); } if (list.length === 0) @@ -456,9 +455,7 @@ Buffer.concat = function concat(list, length) { for (i = 0; i < list.length; i++) { var buf = list[i]; if (!isUint8Array(buf)) { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'list', ['Array', 'Buffer', 'Uint8Array'] - ); + throw new ERR_INVALID_ARG_TYPE('list', ['Array', 'Buffer', 'Uint8Array']); } _copy(buf, buffer, pos); pos += buf.length; @@ -492,9 +489,8 @@ function byteLength(string, encoding) { return string.byteLength; } - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'string', - ['string', 'Buffer', 'ArrayBuffer'], string + throw new ERR_INVALID_ARG_TYPE( + 'string', ['string', 'Buffer', 'ArrayBuffer'], string ); } @@ -609,7 +605,7 @@ function stringSlice(buf, encoding, start, end) { return buf.ucs2Slice(start, end); break; } - throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding); + throw new ERR_UNKNOWN_ENCODING(encoding); } Buffer.prototype.copy = @@ -650,10 +646,7 @@ Buffer.prototype.toString = function toString(encoding, start, end) { Buffer.prototype.equals = function equals(b) { if (!isUint8Array(b)) { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'otherBuffer', - ['Buffer', 'Uint8Array'], b - ); + throw new ERR_INVALID_ARG_TYPE('otherBuffer', ['Buffer', 'Uint8Array'], b); } if (this === b) return true; @@ -678,10 +671,7 @@ Buffer.prototype.compare = function compare(target, thisStart, thisEnd) { if (!isUint8Array(target)) { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'target', - ['Buffer', 'Uint8Array'], target - ); + throw new ERR_INVALID_ARG_TYPE('target', ['Buffer', 'Uint8Array'], target); } if (arguments.length === 1) return _compare(this, target); @@ -689,28 +679,28 @@ Buffer.prototype.compare = function compare(target, if (start === undefined) start = 0; else if (start < 0) - throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE'); + throw new ERR_INDEX_OUT_OF_RANGE(); else start >>>= 0; if (end === undefined) end = target.length; else if (end > target.length) - throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE'); + throw new ERR_INDEX_OUT_OF_RANGE(); else end >>>= 0; if (thisStart === undefined) thisStart = 0; else if (thisStart < 0) - throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE'); + throw new ERR_INDEX_OUT_OF_RANGE(); else thisStart >>>= 0; if (thisEnd === undefined) thisEnd = this.length; else if (thisEnd > this.length) - throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE'); + throw new ERR_INDEX_OUT_OF_RANGE(); else thisEnd >>>= 0; @@ -759,9 +749,8 @@ function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { return indexOfNumber(buffer, val, byteOffset, dir); } - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'value', - ['string', 'Buffer', 'Uint8Array'], val + throw new ERR_INVALID_ARG_TYPE( + 'value', ['string', 'Buffer', 'Uint8Array'], val ); } @@ -787,7 +776,7 @@ function slowIndexOf(buffer, val, byteOffset, encoding, dir) { default: if (loweredCase) { - throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding); + throw new ERR_UNKNOWN_ENCODING(encoding); } encoding = ('' + encoding).toLowerCase(); @@ -830,10 +819,9 @@ function _fill(buf, val, start, end, encoding) { const normalizedEncoding = normalizeEncoding(encoding); if (normalizedEncoding === undefined) { if (typeof encoding !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'encoding', 'string', - encoding); + throw new ERR_INVALID_ARG_TYPE('encoding', 'string', encoding); } - throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding); + throw new ERR_UNKNOWN_ENCODING(encoding); } if (val.length === 0) { @@ -861,11 +849,11 @@ function _fill(buf, val, start, end, encoding) { // Invalid ranges are not set to a default, so can range check early. if (end === undefined) { if (start < 0) - throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE'); + throw new ERR_INDEX_OUT_OF_RANGE(); end = buf.length; } else { if (start < 0 || end > buf.length || end < 0) - throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE'); + throw new ERR_INDEX_OUT_OF_RANGE(); end = end >>> 0; } start = start >>> 0; @@ -876,8 +864,8 @@ function _fill(buf, val, start, end, encoding) { const res = bindingFill(buf, val, start, end, encoding); if (res < 0) { if (res === -1) - throw new errors.TypeError('ERR_INVALID_ARG_VALUE', 'value', val); - throw new errors.RangeError('ERR_INDEX_OUT_OF_RANGE'); + throw new ERR_INVALID_ARG_VALUE('value', val); + throw new ERR_INDEX_OUT_OF_RANGE(); } return buf; @@ -909,13 +897,12 @@ Buffer.prototype.write = function write(string, offset, length, encoding) { length = remaining; if (string.length > 0 && (length < 0 || offset < 0)) - throw new errors.RangeError('ERR_BUFFER_OUT_OF_BOUNDS', 'length', true); + throw new ERR_BUFFER_OUT_OF_BOUNDS('length', true); } else { // if someone is still calling the obsolete form of write(), tell them. // we don't want eg buf.write("foo", "utf8", 10) to silently turn into // buf.write("foo", "utf8"), so we can't ignore extra args - throw new errors.Error( - 'ERR_NO_LONGER_SUPPORTED', + throw new ERR_NO_LONGER_SUPPORTED( 'Buffer.write(string, encoding, offset[, length])' ); } @@ -964,7 +951,7 @@ Buffer.prototype.write = function write(string, offset, length, encoding) { return this.hexWrite(string, offset, length); break; } - throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding); + throw new ERR_UNKNOWN_ENCODING(encoding); }; Buffer.prototype.toJSON = function toJSON() { @@ -1015,7 +1002,7 @@ Buffer.prototype.swap16 = function swap16() { // dropping down to the native code is faster. const len = this.length; if (len % 2 !== 0) - throw new errors.RangeError('ERR_INVALID_BUFFER_SIZE', '16-bits'); + throw new ERR_INVALID_BUFFER_SIZE('16-bits'); if (len < 128) { for (var i = 0; i < len; i += 2) swap(this, i, i + 1); @@ -1030,7 +1017,7 @@ Buffer.prototype.swap32 = function swap32() { // dropping down to the native code is faster. const len = this.length; if (len % 4 !== 0) - throw new errors.RangeError('ERR_INVALID_BUFFER_SIZE', '32-bits'); + throw new ERR_INVALID_BUFFER_SIZE('32-bits'); if (len < 192) { for (var i = 0; i < len; i += 4) { swap(this, i, i + 3); @@ -1047,7 +1034,7 @@ Buffer.prototype.swap64 = function swap64() { // dropping down to the native code is faster. const len = this.length; if (len % 8 !== 0) - throw new errors.RangeError('ERR_INVALID_BUFFER_SIZE', '64-bits'); + throw new ERR_INVALID_BUFFER_SIZE('64-bits'); if (len < 192) { for (var i = 0; i < len; i += 8) { swap(this, i, i + 7); @@ -1073,8 +1060,8 @@ if (process.binding('config').hasIntl) { // Buffer instance. transcode = function transcode(source, fromEncoding, toEncoding) { if (!isUint8Array(source)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'source', - ['Buffer', 'Uint8Array'], source); + throw new ERR_INVALID_ARG_TYPE('source', + ['Buffer', 'Uint8Array'], source); } if (source.length === 0) return Buffer.alloc(0); diff --git a/lib/child_process.js b/lib/child_process.js index b190d9c70a1b43..c18329554a46b9 100644 --- a/lib/child_process.js +++ b/lib/child_process.js @@ -31,7 +31,14 @@ const { createPromise, const debug = util.debuglog('child_process'); const { Buffer } = require('buffer'); const { Pipe, constants: PipeConstants } = process.binding('pipe_wrap'); -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_VALUE, + ERR_CHILD_PROCESS_IPC_REQUIRED, + ERR_CHILD_PROCESS_STDIO_MAXBUFFER, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_OPT_VALUE, + ERR_OUT_OF_RANGE +} = require('internal/errors').codes; const child_process = require('internal/child_process'); const { _validateStdio, @@ -48,7 +55,7 @@ function stdioStringToArray(option) { case 'inherit': return [option, option, option, 'ipc']; default: - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'stdio', option); + throw new ERR_INVALID_OPT_VALUE('stdio', option); } } @@ -65,9 +72,7 @@ exports.fork = function(modulePath /*, args, options*/) { if (pos < arguments.length && arguments[pos] != null) { if (typeof arguments[pos] !== 'object') { - throw new errors.TypeError('ERR_INVALID_ARG_VALUE', - `arguments[${pos}]`, - arguments[pos]); + throw new ERR_INVALID_ARG_VALUE(`arguments[${pos}]`, arguments[pos]); } options = util._extend({}, arguments[pos++]); @@ -95,8 +100,7 @@ exports.fork = function(modulePath /*, args, options*/) { options.stdio = options.silent ? stdioStringToArray('pipe') : stdioStringToArray('inherit'); } else if (options.stdio.indexOf('ipc') === -1) { - throw new errors.Error('ERR_CHILD_PROCESS_IPC_REQUIRED', - 'options.stdio'); + throw new ERR_CHILD_PROCESS_IPC_REQUIRED('options.stdio'); } options.execPath = options.execPath || process.execPath; @@ -200,7 +204,7 @@ exports.execFile = function(file /*, args, options, callback*/) { } if (!callback && pos < arguments.length && arguments[pos] != null) { - throw new errors.TypeError('ERR_INVALID_ARG_VALUE', 'args', arguments[pos]); + throw new ERR_INVALID_ARG_VALUE('args', arguments[pos]); } // Validate the timeout, if present. @@ -327,8 +331,7 @@ exports.execFile = function(file /*, args, options, callback*/) { stdoutLen += encoding ? Buffer.byteLength(chunk, encoding) : chunk.length; if (stdoutLen > options.maxBuffer) { - ex = new errors.RangeError('ERR_CHILD_PROCESS_STDIO_MAXBUFFER', - 'stdout'); + ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER('stdout'); kill(); } else if (encoding) { _stdout += chunk; @@ -346,8 +349,7 @@ exports.execFile = function(file /*, args, options, callback*/) { stderrLen += encoding ? Buffer.byteLength(chunk, encoding) : chunk.length; if (stderrLen > options.maxBuffer) { - ex = new errors.RangeError('ERR_CHILD_PROCESS_STDIO_MAXBUFFER', - 'stderr'); + ex = new ERR_CHILD_PROCESS_STDIO_MAXBUFFER('stderr'); kill(); } else if (encoding) { _stderr += chunk; @@ -384,13 +386,13 @@ function _convertCustomFds(options) { function normalizeSpawnArguments(file, args, options) { if (typeof file !== 'string' || file.length === 0) - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'file', 'string', file); + throw new ERR_INVALID_ARG_TYPE('file', 'string', file); if (Array.isArray(args)) { args = args.slice(0); } else if (args !== undefined && (args === null || typeof args !== 'object')) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'args', 'object', args); + throw new ERR_INVALID_ARG_TYPE('args', 'object', args); } else { options = args; args = []; @@ -399,77 +401,58 @@ function normalizeSpawnArguments(file, args, options) { if (options === undefined) options = {}; else if (options === null || typeof options !== 'object') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options', - 'object', - options); + throw new ERR_INVALID_ARG_TYPE('options', 'object', options); // Validate the cwd, if present. if (options.cwd != null && typeof options.cwd !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.cwd', - 'string', - options.cwd); + throw new ERR_INVALID_ARG_TYPE('options.cwd', 'string', options.cwd); } // Validate detached, if present. if (options.detached != null && typeof options.detached !== 'boolean') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.detached', - 'boolean', - options.detached); + throw new ERR_INVALID_ARG_TYPE('options.detached', + 'boolean', options.detached); } // Validate the uid, if present. if (options.uid != null && !Number.isInteger(options.uid)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.uid', - 'integer', - options.uid); + throw new ERR_INVALID_ARG_TYPE('options.uid', 'integer', options.uid); } // Validate the gid, if present. if (options.gid != null && !Number.isInteger(options.gid)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.gid', - 'integer', - options.gid); + throw new ERR_INVALID_ARG_TYPE('options.gid', 'integer', options.gid); } // Validate the shell, if present. if (options.shell != null && typeof options.shell !== 'boolean' && typeof options.shell !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.shell', - ['boolean', 'string'], - options.shell); + throw new ERR_INVALID_ARG_TYPE('options.shell', + ['boolean', 'string'], options.shell); } // Validate argv0, if present. if (options.argv0 != null && typeof options.argv0 !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.argv0', - 'string', - options.argv0); + throw new ERR_INVALID_ARG_TYPE('options.argv0', 'string', options.argv0); } // Validate windowsHide, if present. if (options.windowsHide != null && typeof options.windowsHide !== 'boolean') { - throw new TypeError('"windowsHide" must be a boolean'); + throw new ERR_INVALID_ARG_TYPE('options.windowsHide', + 'boolean', options.windowsHide); } // Validate windowsVerbatimArguments, if present. if (options.windowsVerbatimArguments != null && typeof options.windowsVerbatimArguments !== 'boolean') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.windowsVerbatimArguments', - 'boolean', - options.windowsVerbatimArguments); + throw new ERR_INVALID_ARG_TYPE('options.windowsVerbatimArguments', + 'boolean', + options.windowsVerbatimArguments); } // Make a shallow copy so we don't clobber the user's options object. @@ -584,10 +567,9 @@ function spawnSync(/*file, args, options*/) { } else if (typeof input === 'string') { pipe.input = Buffer.from(input, options.encoding); } else { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - ('options.stdio[' + i + ']'), - ['Buffer', 'Uint8Array', 'string'], - input); + throw new ERR_INVALID_ARG_TYPE(`options.stdio[${i}]`, + ['Buffer', 'Uint8Array', 'string'], + input); } } } @@ -655,20 +637,16 @@ exports.execSync = execSync; function validateTimeout(timeout) { if (timeout != null && !(Number.isInteger(timeout) && timeout >= 0)) { - throw new errors.RangeError('ERR_OUT_OF_RANGE', - 'timeout', - 'an unsigned integer', - timeout); + throw new ERR_OUT_OF_RANGE('timeout', 'an unsigned integer', timeout); } } function validateMaxBuffer(maxBuffer) { if (maxBuffer != null && !(typeof maxBuffer === 'number' && maxBuffer >= 0)) { - throw new errors.RangeError('ERR_OUT_OF_RANGE', - 'options.maxBuffer', - 'a positive number', - maxBuffer); + throw new ERR_OUT_OF_RANGE('options.maxBuffer', + 'a positive number', + maxBuffer); } } @@ -677,9 +655,8 @@ function sanitizeKillSignal(killSignal) { if (typeof killSignal === 'string' || typeof killSignal === 'number') { return convertToValidSignal(killSignal); } else if (killSignal != null) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.killSignal', - ['string', 'number'], - killSignal); + throw new ERR_INVALID_ARG_TYPE('options.killSignal', + ['string', 'number'], + killSignal); } } diff --git a/lib/crypto.js b/lib/crypto.js index 0156fe6f09c51e..d22ffea9700ee6 100644 --- a/lib/crypto.js +++ b/lib/crypto.js @@ -30,7 +30,10 @@ const { } = require('internal/util'); assertCrypto(); -const errors = require('internal/errors'); +const { + ERR_CRYPTO_FIPS_FORCED, + ERR_CRYPTO_FIPS_UNAVAILABLE +} = require('internal/errors').codes; const constants = process.binding('constants').crypto; const { fipsMode, @@ -183,12 +186,12 @@ module.exports = exports = { }; function setFipsDisabled() { - throw new errors.Error('ERR_CRYPTO_FIPS_UNAVAILABLE'); + throw new ERR_CRYPTO_FIPS_UNAVAILABLE(); } function setFipsForced(val) { if (val) return; - throw new errors.Error('ERR_CRYPTO_FIPS_FORCED'); + throw new ERR_CRYPTO_FIPS_FORCED(); } function getFipsDisabled() { diff --git a/lib/dgram.js b/lib/dgram.js index a31384a586f4c1..78730635cbe268 100644 --- a/lib/dgram.js +++ b/lib/dgram.js @@ -23,6 +23,17 @@ const assert = require('assert'); const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_MISSING_ARGS, + ERR_SOCKET_ALREADY_BOUND, + ERR_SOCKET_BAD_BUFFER_SIZE, + ERR_SOCKET_BAD_PORT, + ERR_SOCKET_BAD_TYPE, + ERR_SOCKET_BUFFER_SIZE, + ERR_SOCKET_CANNOT_SEND, + ERR_SOCKET_DGRAM_NOT_RUNNING +} = errors.codes; const { Buffer } = require('buffer'); const dns = require('dns'); const util = require('util'); @@ -65,7 +76,7 @@ function newHandle(type, lookup) { if (lookup === undefined) lookup = dns.lookup; else if (typeof lookup !== 'function') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'lookup', 'Function'); + throw new ERR_INVALID_ARG_TYPE('lookup', 'Function'); if (type === 'udp4') { const handle = new UDP(); @@ -81,7 +92,7 @@ function newHandle(type, lookup) { return handle; } - throw new errors.TypeError('ERR_SOCKET_BAD_TYPE'); + throw new ERR_SOCKET_BAD_TYPE(); } @@ -173,13 +184,12 @@ function replaceHandle(self, newHandle) { function bufferSize(self, size, buffer) { if (size >>> 0 !== size) - throw new errors.TypeError('ERR_SOCKET_BAD_BUFFER_SIZE'); + throw new ERR_SOCKET_BAD_BUFFER_SIZE(); const ctx = {}; const ret = self._handle.bufferSize(size, buffer, ctx); if (ret === undefined) { - throw new errors.Error('ERR_SOCKET_BUFFER_SIZE', - new errors.SystemError(ctx)); + throw new ERR_SOCKET_BUFFER_SIZE(new errors.SystemError(ctx)); } return ret; } @@ -190,7 +200,7 @@ Socket.prototype.bind = function(port_, address_ /*, callback*/) { this._healthCheck(); if (this._bindState !== BIND_STATE_UNBOUND) - throw new errors.Error('ERR_SOCKET_ALREADY_BOUND'); + throw new ERR_SOCKET_ALREADY_BOUND(); this._bindState = BIND_STATE_BINDING; @@ -290,19 +300,19 @@ Socket.prototype.sendto = function(buffer, address, callback) { if (typeof offset !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'offset', 'number'); + throw new ERR_INVALID_ARG_TYPE('offset', 'number'); } if (typeof length !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'length', 'number'); + throw new ERR_INVALID_ARG_TYPE('length', 'number'); } if (typeof port !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'port', 'number'); + throw new ERR_INVALID_ARG_TYPE('port', 'number'); } if (typeof address !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'address', 'string'); + throw new ERR_INVALID_ARG_TYPE('address', 'string'); } this.send(buffer, offset, length, port, address, callback); @@ -313,9 +323,8 @@ function sliceBuffer(buffer, offset, length) { if (typeof buffer === 'string') { buffer = Buffer.from(buffer); } else if (!isUint8Array(buffer)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'buffer', - ['Buffer', 'Uint8Array', 'string']); + throw new ERR_INVALID_ARG_TYPE('buffer', + ['Buffer', 'Uint8Array', 'string']); } offset = offset >>> 0; @@ -363,7 +372,7 @@ function onListenSuccess() { function onListenError(err) { this.removeListener('listening', onListenSuccess); this._queue = undefined; - this.emit('error', new errors.Error('ERR_SOCKET_CANNOT_SEND')); + this.emit('error', new ERR_SOCKET_CANNOT_SEND()); } @@ -406,21 +415,19 @@ Socket.prototype.send = function(buffer, if (typeof buffer === 'string') { list = [ Buffer.from(buffer) ]; } else if (!isUint8Array(buffer)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'buffer', - ['Buffer', 'Uint8Array', 'string']); + throw new ERR_INVALID_ARG_TYPE('buffer', + ['Buffer', 'Uint8Array', 'string']); } else { list = [ buffer ]; } } else if (!(list = fixBufferList(buffer))) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'buffer list arguments', - ['Buffer', 'string']); + throw new ERR_INVALID_ARG_TYPE('buffer list arguments', + ['Buffer', 'string']); } port = port >>> 0; if (port === 0 || port > 65535) - throw new errors.RangeError('ERR_SOCKET_BAD_PORT', port); + throw new ERR_SOCKET_BAD_PORT(port); // Normalize callback so it's either a function or undefined but not anything // else. @@ -431,9 +438,7 @@ Socket.prototype.send = function(buffer, callback = address; address = undefined; } else if (address && typeof address !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'address', - ['string', 'falsy']); + throw new ERR_INVALID_ARG_TYPE('address', ['string', 'falsy']); } this._healthCheck(); @@ -555,7 +560,7 @@ Socket.prototype.setBroadcast = function(arg) { Socket.prototype.setTTL = function(ttl) { if (typeof ttl !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'ttl', 'number', ttl); + throw new ERR_INVALID_ARG_TYPE('ttl', 'number', ttl); } var err = this._handle.setTTL(ttl); @@ -569,7 +574,7 @@ Socket.prototype.setTTL = function(ttl) { Socket.prototype.setMulticastTTL = function(ttl) { if (typeof ttl !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'ttl', 'number', ttl); + throw new ERR_INVALID_ARG_TYPE('ttl', 'number', ttl); } var err = this._handle.setMulticastTTL(ttl); @@ -595,9 +600,7 @@ Socket.prototype.setMulticastInterface = function(interfaceAddress) { this._healthCheck(); if (typeof interfaceAddress !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'interfaceAddress', - 'string'); + throw new ERR_INVALID_ARG_TYPE('interfaceAddress', 'string'); } const err = this._handle.setMulticastInterface(interfaceAddress); @@ -611,7 +614,7 @@ Socket.prototype.addMembership = function(multicastAddress, this._healthCheck(); if (!multicastAddress) { - throw new errors.TypeError('ERR_MISSING_ARGS', 'multicastAddress'); + throw new ERR_MISSING_ARGS('multicastAddress'); } var err = this._handle.addMembership(multicastAddress, interfaceAddress); @@ -626,7 +629,7 @@ Socket.prototype.dropMembership = function(multicastAddress, this._healthCheck(); if (!multicastAddress) { - throw new errors.TypeError('ERR_MISSING_ARGS', 'multicastAddress'); + throw new ERR_MISSING_ARGS('multicastAddress'); } var err = this._handle.dropMembership(multicastAddress, interfaceAddress); @@ -639,7 +642,7 @@ Socket.prototype.dropMembership = function(multicastAddress, Socket.prototype._healthCheck = function() { if (!this._handle) { // Error message from dgram_legacy.js. - throw new errors.Error('ERR_SOCKET_DGRAM_NOT_RUNNING'); + throw new ERR_SOCKET_DGRAM_NOT_RUNNING(); } }; diff --git a/lib/dns.js b/lib/dns.js index 51c144f4e394eb..cb8b2ca0beb4cd 100644 --- a/lib/dns.js +++ b/lib/dns.js @@ -25,6 +25,15 @@ const cares = process.binding('cares_wrap'); const { isIP, isIPv4, isLegalPort } = require('internal/net'); const { customPromisifyArgs } = require('internal/util'); const errors = require('internal/errors'); +const { + ERR_DNS_SET_SERVERS_FAILED, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CALLBACK, + ERR_INVALID_IP_ADDRESS, + ERR_INVALID_OPT_VALUE, + ERR_MISSING_ARGS, + ERR_SOCKET_BAD_PORT +} = errors.codes; const { GetAddrInfoReqWrap, @@ -76,13 +85,12 @@ function lookup(hostname, options, callback) { // Parse arguments if (hostname && typeof hostname !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'hostname', - ['string', 'falsy'], hostname); + throw new ERR_INVALID_ARG_TYPE('hostname', ['string', 'falsy'], hostname); } else if (typeof options === 'function') { callback = options; family = 0; } else if (typeof callback !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } else if (options !== null && typeof options === 'object') { hints = options.hints >>> 0; family = options.family >>> 0; @@ -93,14 +101,14 @@ function lookup(hostname, options, callback) { hints !== cares.AI_ADDRCONFIG && hints !== cares.AI_V4MAPPED && hints !== (cares.AI_ADDRCONFIG | cares.AI_V4MAPPED)) { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'hints', hints); + throw new ERR_INVALID_OPT_VALUE('hints', hints); } } else { family = options >>> 0; } if (family !== 0 && family !== 4 && family !== 6) - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'family', family); + throw new ERR_INVALID_OPT_VALUE('family', family); if (!hostname) { if (all) { @@ -151,16 +159,16 @@ function onlookupservice(err, host, service) { // lookupService(address, port, callback) function lookupService(host, port, callback) { if (arguments.length !== 3) - throw new errors.TypeError('ERR_MISSING_ARGS', 'host', 'port', 'callback'); + throw new ERR_MISSING_ARGS('host', 'port', 'callback'); if (isIP(host) === 0) - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'host', host); + throw new ERR_INVALID_OPT_VALUE('host', host); if (!isLegalPort(port)) - throw new errors.RangeError('ERR_SOCKET_BAD_PORT', port); + throw new ERR_SOCKET_BAD_PORT(port); if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); port = +port; @@ -209,10 +217,9 @@ function resolver(bindingName) { } if (typeof name !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', - 'string', name); + throw new ERR_INVALID_ARG_TYPE('name', 'string', name); } else if (typeof callback !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } var req = new QueryReqWrap(); @@ -253,14 +260,13 @@ function resolve(hostname, rrtype, callback) { resolver = resolveMap.A; callback = rrtype; } else { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'rrtype', - 'string', rrtype); + throw new ERR_INVALID_ARG_TYPE('rrtype', 'string', rrtype); } if (typeof resolver === 'function') { return resolver.call(this, hostname, callback); } else { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'rrtype', rrtype); + throw new ERR_INVALID_OPT_VALUE('rrtype', rrtype); } } @@ -310,7 +316,7 @@ function setServers(servers) { return newSet.push([ipVersion, s, parseInt(p)]); } - throw new errors.Error('ERR_INVALID_IP_ADDRESS', serv); + throw new ERR_INVALID_IP_ADDRESS.Error(serv); }); const errorNumber = this._handle.setServers(newSet); @@ -320,7 +326,7 @@ function setServers(servers) { this._handle.setServers(orig.join(',')); var err = cares.strerror(errorNumber); - throw new errors.Error('ERR_DNS_SET_SERVERS_FAILED', err, servers); + throw new ERR_DNS_SET_SERVERS_FAILED(err, servers); } } diff --git a/lib/domain.js b/lib/domain.js index be109c9ce056bd..360896d16a06e3 100644 --- a/lib/domain.js +++ b/lib/domain.js @@ -28,7 +28,11 @@ const util = require('util'); const EventEmitter = require('events'); -const errors = require('internal/errors'); +const { + ERR_DOMAIN_CALLBACK_NOT_AVAILABLE, + ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE, + ERR_UNHANDLED_ERROR +} = require('internal/errors').codes; const { createHook } = require('async_hooks'); // overwrite process.domain with a getter/setter that will allow for more @@ -80,7 +84,7 @@ const asyncHook = createHook({ // When domains are in use, they claim full ownership of the // uncaught exception capture callback. if (process.hasUncaughtExceptionCaptureCallback()) { - throw new errors.Error('ERR_DOMAIN_CALLBACK_NOT_AVAILABLE'); + throw new ERR_DOMAIN_CALLBACK_NOT_AVAILABLE(); } // Get the stack trace at the point where `domain` was required. @@ -88,8 +92,7 @@ const domainRequireStack = new Error('require(`domain`) at this point').stack; const { setUncaughtExceptionCaptureCallback } = process; process.setUncaughtExceptionCaptureCallback = function(fn) { - const err = - new errors.Error('ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE'); + const err = new ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE(); err.stack = err.stack + '\n' + '-'.repeat(40) + '\n' + domainRequireStack; throw err; }; @@ -439,7 +442,7 @@ EventEmitter.prototype.emit = function emit(...args) { if (type === 'error') { const er = args.length > 1 && args[1] ? - args[1] : new errors.Error('ERR_UNHANDLED_ERROR'); + args[1] : new ERR_UNHANDLED_ERROR(); if (typeof er === 'object') { er.domainEmitter = this; diff --git a/lib/events.js b/lib/events.js index 0a220b5d821e7f..2a8cf60c91cb78 100644 --- a/lib/events.js +++ b/lib/events.js @@ -44,7 +44,7 @@ var defaultMaxListeners = 10; var errors; function lazyErrors() { if (errors === undefined) - errors = require('internal/errors'); + errors = require('internal/errors').codes; return errors; } @@ -56,10 +56,9 @@ Object.defineProperty(EventEmitter, 'defaultMaxListeners', { set: function(arg) { if (typeof arg !== 'number' || arg < 0 || Number.isNaN(arg)) { const errors = lazyErrors(); - throw new errors.RangeError('ERR_OUT_OF_RANGE', - 'defaultMaxListeners', - 'a non-negative number', - arg); + throw new errors.ERR_OUT_OF_RANGE('defaultMaxListeners', + 'a non-negative number', + arg); } defaultMaxListeners = arg; } @@ -81,8 +80,7 @@ EventEmitter.init = function() { EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { if (typeof n !== 'number' || n < 0 || Number.isNaN(n)) { const errors = lazyErrors(); - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'n', - 'a non-negative number', n); + throw new errors.ERR_OUT_OF_RANGE('n', 'a non-negative number', n); } this._maxListeners = n; return this; @@ -170,7 +168,7 @@ EventEmitter.prototype.emit = function emit(type, ...args) { } // At least give some kind of context to the user const errors = lazyErrors(); - const err = new errors.Error('ERR_UNHANDLED_ERROR', er); + const err = new errors.ERR_UNHANDLED_ERROR(er); err.context = er; throw err; // Unhandled 'error' event } @@ -199,7 +197,7 @@ function _addListener(target, type, listener, prepend) { if (typeof listener !== 'function') { const errors = lazyErrors(); - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', 'Function'); + throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function'); } events = target._events; @@ -288,7 +286,7 @@ function _onceWrap(target, type, listener) { EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') { const errors = lazyErrors(); - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', 'Function'); + throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function'); } this.on(type, _onceWrap(this, type, listener)); return this; @@ -298,8 +296,7 @@ EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') { const errors = lazyErrors(); - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', - 'Function'); + throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function'); } this.prependListener(type, _onceWrap(this, type, listener)); return this; @@ -312,8 +309,7 @@ EventEmitter.prototype.removeListener = if (typeof listener !== 'function') { const errors = lazyErrors(); - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'listener', - 'Function'); + throw new errors.ERR_INVALID_ARG_TYPE('listener', 'Function'); } events = this._events; diff --git a/lib/fs.js b/lib/fs.js index afbc412058ba27..3771efad10d762 100644 --- a/lib/fs.js +++ b/lib/fs.js @@ -35,6 +35,11 @@ const binding = process.binding('fs'); const fs = exports; const { Buffer } = require('buffer'); const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CALLBACK, + ERR_OUT_OF_RANGE +} = errors.codes; const { Readable, Writable } = require('stream'); const EventEmitter = require('events'); const { FSReqWrap, statValues } = binding; @@ -109,7 +114,7 @@ function maybeCallback(cb) { if (typeof cb === 'function') return cb; - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } // Ensure that callbacks run in the global context. Only use this function @@ -117,7 +122,7 @@ function maybeCallback(cb) { // invoked from JS already run in the proper scope. function makeCallback(cb) { if (typeof cb !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } return function(...args) { @@ -130,7 +135,7 @@ function makeCallback(cb) { // transformed anyway. function makeStatsCallback(cb) { if (typeof cb !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } return function(err) { @@ -1000,7 +1005,7 @@ fs.fchmod = function(fd, mode, callback) { validateUint32(mode, 'mode'); // values for mode < 0 are already checked via the validateUint32 function if (mode > 0o777) - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'mode'); + throw new ERR_OUT_OF_RANGE('mode'); const req = new FSReqWrap(); req.oncomplete = makeCallback(callback); @@ -1012,7 +1017,7 @@ fs.fchmodSync = function(fd, mode) { validateUint32(fd, 'fd'); validateUint32(mode, 'mode'); if (mode < 0 || mode > 0o777) - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'mode'); + throw new ERR_OUT_OF_RANGE('mode'); const ctx = {}; binding.fchmod(fd, mode, undefined, ctx); handleErrorFromBinding(ctx); @@ -1457,10 +1462,7 @@ fs.watchFile = function(filename, options, listener) { } if (typeof listener !== 'function') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'listener', - 'Function', - listener); + throw new ERR_INVALID_ARG_TYPE('listener', 'Function', listener); } stat = statWatchers.get(filename); @@ -1835,10 +1837,7 @@ fs.mkdtemp = function(prefix, options, callback) { callback = makeCallback(typeof options === 'function' ? options : callback); options = getOptions(options, {}); if (!prefix || typeof prefix !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'prefix', - 'string', - prefix); + throw new ERR_INVALID_ARG_TYPE('prefix', 'string', prefix); } nullCheck(prefix, 'prefix'); var req = new FSReqWrap(); @@ -1850,10 +1849,7 @@ fs.mkdtemp = function(prefix, options, callback) { fs.mkdtempSync = function(prefix, options) { options = getOptions(options, {}); if (!prefix || typeof prefix !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'prefix', - 'string', - prefix); + throw new ERR_INVALID_ARG_TYPE('prefix', 'string', prefix); } nullCheck(prefix, 'prefix'); const path = `${prefix}XXXXXX`; @@ -1876,7 +1872,7 @@ fs.copyFile = function(src, dest, flags, callback) { callback = flags; flags = 0; } else if (typeof callback !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } src = getPathFromURL(src); @@ -1951,26 +1947,17 @@ function ReadStream(path, options) { if (this.start !== undefined) { if (typeof this.start !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'start', - 'number', - this.start); + throw new ERR_INVALID_ARG_TYPE('start', 'number', this.start); } if (this.end === undefined) { this.end = Infinity; } else if (typeof this.end !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'end', - 'number', - this.end); + throw new ERR_INVALID_ARG_TYPE('end', 'number', this.end); } if (this.start > this.end) { const errVal = `{start: ${this.start}, end: ${this.end}}`; - throw new errors.RangeError('ERR_OUT_OF_RANGE', - 'start', - '<= "end"', - errVal); + throw new ERR_OUT_OF_RANGE('start', '<= "end"', errVal); } this.pos = this.start; @@ -2113,17 +2100,11 @@ function WriteStream(path, options) { if (this.start !== undefined) { if (typeof this.start !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'start', - 'number', - this.start); + throw new ERR_INVALID_ARG_TYPE('start', 'number', this.start); } if (this.start < 0) { const errVal = `{start: ${this.start}}`; - throw new errors.RangeError('ERR_OUT_OF_RANGE', - 'start', - '>= 0', - errVal); + throw new ERR_OUT_OF_RANGE('start', '>= 0', errVal); } this.pos = this.start; @@ -2164,10 +2145,7 @@ WriteStream.prototype.open = function() { WriteStream.prototype._write = function(data, encoding, cb) { if (!(data instanceof Buffer)) { - const err = new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'data', - 'Buffer', - data); + const err = new ERR_INVALID_ARG_TYPE('data', 'Buffer', data); return this.emit('error', err); } diff --git a/lib/https.js b/lib/https.js index 84ddeb5036a900..b9e2d56492dbec 100644 --- a/lib/https.js +++ b/lib/https.js @@ -35,7 +35,7 @@ const { ClientRequest } = require('_http_client'); const { inherits } = util; const debug = util.debuglog('https'); const { urlToOptions, searchParamsSymbol } = require('internal/url'); -const errors = require('internal/errors'); +const { ERR_INVALID_DOMAIN_NAME } = require('internal/errors').codes; const { IncomingMessage, ServerResponse } = require('http'); const { kIncomingMessage } = require('_http_common'); const { kServerResponse } = require('_http_server'); @@ -262,7 +262,7 @@ function request(options, cb) { if (typeof options === 'string') { options = url.parse(options); if (!options.hostname) { - throw new errors.Error('ERR_INVALID_DOMAIN_NAME'); + throw new ERR_INVALID_DOMAIN_NAME(); } } else if (options && options[searchParamsSymbol] && options[searchParamsSymbol][searchParamsSymbol]) { diff --git a/lib/inspector.js b/lib/inspector.js index 5206024f7b9fe7..157ca286326864 100644 --- a/lib/inspector.js +++ b/lib/inspector.js @@ -1,12 +1,19 @@ 'use strict'; const EventEmitter = require('events'); -const errors = require('internal/errors'); +const { + ERR_INSPECTOR_ALREADY_CONNECTED, + ERR_INSPECTOR_CLOSED, + ERR_INSPECTOR_NOT_AVAILABLE, + ERR_INSPECTOR_NOT_CONNECTED, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CALLBACK +} = require('internal/errors').codes; const util = require('util'); const { Connection, open, url } = process.binding('inspector'); if (!Connection) - throw new errors.Error('ERR_INSPECTOR_NOT_AVAILABLE'); + throw new ERR_INSPECTOR_NOT_AVAILABLE(); const connectionSymbol = Symbol('connectionProperty'); const messageCallbacksSymbol = Symbol('messageCallbacks'); @@ -23,7 +30,7 @@ class Session extends EventEmitter { connect() { if (this[connectionSymbol]) - throw new errors.Error('ERR_INSPECTOR_ALREADY_CONNECTED'); + throw new ERR_INSPECTOR_ALREADY_CONNECTED(); this[connectionSymbol] = new Connection((message) => this[onMessageSymbol](message)); } @@ -47,23 +54,21 @@ class Session extends EventEmitter { post(method, params, callback) { if (typeof method !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'method', 'string', method); + throw new ERR_INVALID_ARG_TYPE('method', 'string', method); } if (!callback && util.isFunction(params)) { callback = params; params = null; } if (params && typeof params !== 'object') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'params', 'Object', params); + throw new ERR_INVALID_ARG_TYPE('params', 'Object', params); } if (callback && typeof callback !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } if (!this[connectionSymbol]) { - throw new errors.Error('ERR_INSPECTOR_NOT_CONNECTED'); + throw new ERR_INSPECTOR_NOT_CONNECTED(); } const id = this[nextIdSymbol]++; const message = { id, method }; @@ -83,7 +88,7 @@ class Session extends EventEmitter { this[connectionSymbol] = null; const remainingCallbacks = this[messageCallbacksSymbol].values(); for (const callback of remainingCallbacks) { - process.nextTick(callback, new errors.Error('ERR_INSPECTOR_CLOSED')); + process.nextTick(callback, new ERR_INSPECTOR_CLOSED()); } this[messageCallbacksSymbol].clear(); this[nextIdSymbol] = 1; diff --git a/lib/module.js b/lib/module.js index be49fa8e8d7e99..8d1002a3839468 100644 --- a/lib/module.js +++ b/lib/module.js @@ -39,7 +39,11 @@ const internalModule = require('internal/module'); const preserveSymlinks = !!process.binding('config').preserveSymlinks; const experimentalModules = !!process.binding('config').experimentalModules; -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE, + ERR_REQUIRE_ESM +} = require('internal/errors').codes; module.exports = Module; @@ -605,11 +609,11 @@ Module.prototype.load = function(filename) { // `exports` property. Module.prototype.require = function(id) { if (typeof id !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'id', 'string', id); + throw new ERR_INVALID_ARG_TYPE('id', 'string', id); } if (id === '') { - throw new errors.Error('ERR_INVALID_ARG_VALUE', - 'id', id, 'must be a non-empty string'); + throw new ERR_INVALID_ARG_VALUE('id', id, + 'must be a non-empty string'); } return Module._load(id, this, /* isMain */ false); }; @@ -697,7 +701,7 @@ Module._extensions['.node'] = function(module, filename) { if (experimentalModules) { Module._extensions['.mjs'] = function(module, filename) { - throw new errors.Error('ERR_REQUIRE_ESM', filename); + throw new ERR_REQUIRE_ESM(filename); }; } diff --git a/lib/net.js b/lib/net.js index 9ff26c74515eaa..7583fcb27d1064 100644 --- a/lib/net.js +++ b/lib/net.js @@ -54,6 +54,16 @@ const { } = require('internal/async_hooks'); const { nextTick } = require('internal/process/next_tick'); const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_FD_TYPE, + ERR_INVALID_IP_ADDRESS, + ERR_INVALID_OPT_VALUE, + ERR_SERVER_ALREADY_LISTEN, + ERR_SERVER_NOT_RUNNING, + ERR_SOCKET_BAD_PORT, + ERR_SOCKET_CLOSED +} = errors.codes; const dns = require('dns'); const kLastWriteQueueSize = Symbol('lastWriteQueueSize'); @@ -88,7 +98,7 @@ function createHandle(fd, is_server) { ); } - throw new errors.TypeError('ERR_INVALID_FD_TYPE', type); + throw new ERR_INVALID_FD_TYPE(type); } @@ -724,7 +734,7 @@ Socket.prototype._writeGeneric = function(writev, data, encoding, cb) { this._unrefTimer(); if (!this._handle) { - this.destroy(new errors.Error('ERR_SOCKET_CLOSED'), cb); + this.destroy(new ERR_SOCKET_CLOSED(), cb); return false; } @@ -1011,10 +1021,7 @@ Socket.prototype.connect = function(...args) { if (pipe) { if (typeof path !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.path', - 'string', - path); + throw new ERR_INVALID_ARG_TYPE('options.path', 'string', path); } defaultTriggerAsyncIdScope( this[async_id_symbol], internalConnect, this, path @@ -1033,25 +1040,20 @@ function lookupAndConnect(self, options) { var localPort = options.localPort; if (localAddress && !isIP(localAddress)) { - throw new errors.TypeError('ERR_INVALID_IP_ADDRESS', localAddress); + throw new ERR_INVALID_IP_ADDRESS(localAddress); } if (localPort && typeof localPort !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.localPort', - 'number', - localPort); + throw new ERR_INVALID_ARG_TYPE('options.localPort', 'number', localPort); } if (typeof port !== 'undefined') { if (typeof port !== 'number' && typeof port !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.port', - ['number', 'string'], - port); + throw new ERR_INVALID_ARG_TYPE('options.port', + ['number', 'string'], port); } if (!isLegalPort(port)) { - throw new errors.RangeError('ERR_SOCKET_BAD_PORT', port); + throw new ERR_SOCKET_BAD_PORT(port); } } port |= 0; @@ -1071,10 +1073,8 @@ function lookupAndConnect(self, options) { } if (options.lookup && typeof options.lookup !== 'function') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.lookup', - 'Function', - options.lookup); + throw new ERR_INVALID_ARG_TYPE('options.lookup', + 'Function', options.lookup); var dnsopts = { family: options.family, @@ -1223,10 +1223,7 @@ function Server(options, connectionListener) { this.on('connection', connectionListener); } } else { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options', - 'Object', - options); + throw new ERR_INVALID_ARG_TYPE('options', 'Object', options); } this._connections = 0; @@ -1443,7 +1440,7 @@ Server.prototype.listen = function(...args) { var cb = normalized[1]; if (this._handle) { - throw new errors.Error('ERR_SERVER_ALREADY_LISTEN'); + throw new ERR_SERVER_ALREADY_LISTEN(); } var hasCallback = (cb !== null); @@ -1484,7 +1481,7 @@ Server.prototype.listen = function(...args) { var backlog; if (typeof options.port === 'number' || typeof options.port === 'string') { if (!isLegalPort(options.port)) { - throw new errors.RangeError('ERR_SOCKET_BAD_PORT', options.port); + throw new ERR_SOCKET_BAD_PORT(options.port); } backlog = options.backlog || backlogFromArgs; // start TCP server listening on host:port @@ -1509,9 +1506,7 @@ Server.prototype.listen = function(...args) { return this; } - throw new errors.Error('ERR_INVALID_OPT_VALUE', - 'options', - util.inspect(options)); + throw new ERR_INVALID_OPT_VALUE('options', util.inspect(options)); }; function lookupAndListen(self, port, address, backlog, exclusive) { @@ -1622,7 +1617,7 @@ Server.prototype.close = function(cb) { if (typeof cb === 'function') { if (!this._handle) { this.once('close', function close() { - cb(new errors.Error('ERR_SERVER_NOT_RUNNING')); + cb(new ERR_SERVER_NOT_RUNNING()); }); } else { this.once('close', cb); diff --git a/lib/path.js b/lib/path.js index 098416adfe1a3a..9f33cb87bc5b79 100644 --- a/lib/path.js +++ b/lib/path.js @@ -21,7 +21,7 @@ 'use strict'; -const errors = require('internal/errors'); +const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes; const { CHAR_UPPERCASE_A, CHAR_LOWERCASE_A, @@ -36,7 +36,7 @@ const { function assertPath(path) { if (typeof path !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'path', 'string'); + throw new ERR_INVALID_ARG_TYPE('path', 'string'); } } @@ -808,7 +808,7 @@ const win32 = { basename: function basename(path, ext) { if (ext !== undefined && typeof ext !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'ext', 'string'); + throw new ERR_INVALID_ARG_TYPE('ext', 'string'); assertPath(path); var start = 0; var end = -1; @@ -961,8 +961,7 @@ const win32 = { format: function format(pathObject) { if (pathObject === null || typeof pathObject !== 'object') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'pathObject', 'Object', - pathObject); + throw new ERR_INVALID_ARG_TYPE('pathObject', 'Object', pathObject); } return _format('\\', pathObject); }, @@ -1356,7 +1355,7 @@ const posix = { basename: function basename(path, ext) { if (ext !== undefined && typeof ext !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'ext', 'string'); + throw new ERR_INVALID_ARG_TYPE('ext', 'string'); assertPath(path); var start = 0; @@ -1487,8 +1486,7 @@ const posix = { format: function format(pathObject) { if (pathObject === null || typeof pathObject !== 'object') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'pathObject', 'Object', - pathObject); + throw new ERR_INVALID_ARG_TYPE('pathObject', 'Object', pathObject); } return _format('/', pathObject); }, diff --git a/lib/perf_hooks.js b/lib/perf_hooks.js index 025fa9edd06de1..8b3c57d0637c29 100644 --- a/lib/perf_hooks.js +++ b/lib/perf_hooks.js @@ -137,7 +137,7 @@ function collectHttp2Stats(entry) { let errors; function lazyErrors() { if (errors === undefined) - errors = require('internal/errors'); + errors = require('internal/errors').codes; return errors; } @@ -322,7 +322,7 @@ class PerformanceObserver extends AsyncResource { constructor(callback) { if (typeof callback !== 'function') { const errors = lazyErrors(); - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new errors.ERR_INVALID_CALLBACK(); } super('PerformanceObserver'); Object.defineProperties(this, { @@ -370,15 +370,14 @@ class PerformanceObserver extends AsyncResource { observe(options) { const errors = lazyErrors(); if (typeof options !== 'object' || options == null) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object'); + throw new errors.ERR_INVALID_ARG_TYPE('options', 'Object'); } if (!Array.isArray(options.entryTypes)) { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'entryTypes', options); + throw new errors.ERR_INVALID_OPT_VALUE('entryTypes', options); } const entryTypes = options.entryTypes.filter(filterTypes).map(mapTypes); if (entryTypes.length === 0) { - throw new errors.Error('ERR_VALID_PERFORMANCE_ENTRY_TYPE'); + throw new errors.ERR_VALID_PERFORMANCE_ENTRY_TYPE(); } this.disconnect(); this[kBuffer][kEntries] = []; @@ -408,7 +407,7 @@ class Performance extends PerformanceObserverEntryList { set maxEntries(val) { if (typeof val !== 'number' || val >>> 0 !== val) { const errors = lazyErrors(); - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'val', 'number'); + throw new errors.ERR_INVALID_ARG_TYPE('val', 'number'); } this[kMaxCount] = Math.max(1, val >>> 0); } @@ -488,7 +487,7 @@ class Performance extends PerformanceObserverEntryList { const marks = this[kIndex][kMarks]; if (!marks.has(endMark) && !(endMark in nodeTiming)) { const errors = lazyErrors(); - throw new errors.Error('ERR_INVALID_PERFORMANCE_MARK', endMark); + throw new errors.ERR_INVALID_PERFORMANCE_MARK(endMark); } _measure(name, startMark, endMark); } @@ -521,7 +520,7 @@ class Performance extends PerformanceObserverEntryList { timerify(fn) { if (typeof fn !== 'function') { const errors = lazyErrors(); - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'fn', 'Function'); + throw new errors.ERR_INVALID_ARG_TYPE('fn', 'Function'); } if (fn[kTimerified]) return fn[kTimerified]; diff --git a/lib/querystring.js b/lib/querystring.js index ec6ad51a89177e..3bedd493f4b34f 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -24,7 +24,7 @@ 'use strict'; const { Buffer } = require('buffer'); -const errors = require('internal/errors'); +const { ERR_INVALID_URI } = require('internal/errors').codes; const { hexTable, isHexTable @@ -177,7 +177,7 @@ function qsEscape(str) { ++i; if (i >= str.length) - throw new errors.URIError('ERR_INVALID_URI'); + throw new ERR_INVALID_URI(); var c2 = str.charCodeAt(i) & 0x3FF; diff --git a/lib/readline.js b/lib/readline.js index 15933e69302d84..124fc8111b2f09 100644 --- a/lib/readline.js +++ b/lib/readline.js @@ -27,7 +27,11 @@ 'use strict'; -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CURSOR_POS, + ERR_INVALID_OPT_VALUE +} = require('internal/errors').codes; const { debug, inherits } = require('util'); const { Buffer } = require('buffer'); const EventEmitter = require('events'); @@ -95,7 +99,7 @@ function Interface(input, output, completer, terminal) { } if (completer && typeof completer !== 'function') { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'completer', completer); + throw new ERR_INVALID_OPT_VALUE('completer', completer); } if (historySize === undefined) { @@ -105,11 +109,7 @@ function Interface(input, output, completer, terminal) { if (typeof historySize !== 'number' || Number.isNaN(historySize) || historySize < 0) { - throw new errors.RangeError( - 'ERR_INVALID_OPT_VALUE', - 'historySize', - historySize - ); + throw new ERR_INVALID_OPT_VALUE.RangeError('historySize', historySize); } // backwards compat; check the isTTY prop of the output stream @@ -288,12 +288,7 @@ Interface.prototype._onLine = function(line) { Interface.prototype._writeToOutput = function _writeToOutput(stringToWrite) { if (typeof stringToWrite !== 'string') { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', - 'stringToWrite', - 'string', - stringToWrite - ); + throw new ERR_INVALID_ARG_TYPE('stringToWrite', 'string', stringToWrite); } if (this.output !== null && this.output !== undefined) { @@ -1067,7 +1062,7 @@ function cursorTo(stream, x, y) { return; if (typeof x !== 'number') - throw new errors.Error('ERR_INVALID_CURSOR_POS'); + throw new ERR_INVALID_CURSOR_POS(); if (typeof y !== 'number') { stream.write(CSI`${x + 1}G`); diff --git a/lib/repl.js b/lib/repl.js index 4bcbd1a2db09f4..7645988752e795 100644 --- a/lib/repl.js +++ b/lib/repl.js @@ -58,7 +58,12 @@ const { Console } = require('console'); const Module = require('module'); const domain = require('domain'); const debug = util.debuglog('repl'); -const errors = require('internal/errors'); +const { + ERR_CANNOT_WATCH_SIGINT, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_REPL_EVAL_CONFIG, + ERR_SCRIPT_EXECUTION_INTERRUPTED +} = require('internal/errors').codes; const { sendInspectorCommand } = require('internal/util/inspector'); const parentModule = module; @@ -145,7 +150,7 @@ function REPLServer(prompt, if (breakEvalOnSigint && eval_) { // Allowing this would not reflect user expectations. // breakEvalOnSigint affects only the behavior of the default eval(). - throw new errors.Error('ERR_INVALID_REPL_EVAL_CONFIG'); + throw new ERR_INVALID_REPL_EVAL_CONFIG(); } var self = this; @@ -287,7 +292,7 @@ function REPLServer(prompt, // Start the SIGINT watchdog before entering raw mode so that a very // quick Ctrl+C doesn't lead to aborting the process completely. if (!utilBinding.startSigintWatchdog()) - throw new errors.Error('ERR_CANNOT_WATCH_SIGINT'); + throw new ERR_CANNOT_WATCH_SIGINT(); previouslyInRawMode = self._setRawMode(false); } @@ -338,7 +343,7 @@ function REPLServer(prompt, if (self.breakEvalOnSigint) { const interrupt = new Promise((resolve, reject) => { sigintListener = () => { - reject(new errors.Error('ERR_SCRIPT_EXECUTION_INTERRUPTED')); + reject(new ERR_SCRIPT_EXECUTION_INTERRUPTED()); }; prioritizedSigintQueue.add(sigintListener); }); @@ -1246,10 +1251,7 @@ REPLServer.prototype.defineCommand = function(keyword, cmd) { if (typeof cmd === 'function') { cmd = { action: cmd }; } else if (typeof cmd.action !== 'function') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'action', - 'Function', - cmd.action); + throw new ERR_INVALID_ARG_TYPE('action', 'Function', cmd.action); } this.commands[keyword] = cmd; }; diff --git a/lib/string_decoder.js b/lib/string_decoder.js index 18097be0e6dd08..a2b7cf7de27b49 100644 --- a/lib/string_decoder.js +++ b/lib/string_decoder.js @@ -34,7 +34,10 @@ const { encodings } = internalBinding('string_decoder'); const internalUtil = require('internal/util'); -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_UNKNOWN_ENCODING +} = require('internal/errors').codes; const isEncoding = Buffer[internalUtil.kIsEncodingSymbol]; const kNativeDecoder = Symbol('kNativeDecoder'); @@ -45,7 +48,7 @@ function normalizeEncoding(enc) { const nenc = internalUtil.normalizeEncoding(enc); if (nenc === undefined) { if (Buffer.isEncoding === isEncoding || !Buffer.isEncoding(enc)) - throw new errors.TypeError('ERR_UNKNOWN_ENCODING', enc); + throw new ERR_UNKNOWN_ENCODING(enc); return enc; } return nenc; @@ -68,8 +71,8 @@ StringDecoder.prototype.write = function write(buf) { if (typeof buf === 'string') return buf; if (!ArrayBuffer.isView(buf)) - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'buf', - ['Buffer', 'Uint8Array', 'ArrayBufferView']); + throw new ERR_INVALID_ARG_TYPE('buf', + ['Buffer', 'Uint8Array', 'ArrayBufferView']); return decode(this[kNativeDecoder], buf); }; diff --git a/lib/timers.js b/lib/timers.js index 2744f231b5c131..32f6ccb00cd4c6 100644 --- a/lib/timers.js +++ b/lib/timers.js @@ -37,7 +37,7 @@ const internalUtil = require('internal/util'); const { createPromise, promiseResolve } = process.binding('util'); const assert = require('assert'); const util = require('util'); -const errors = require('internal/errors'); +const { ERR_INVALID_CALLBACK } = require('internal/errors').codes; const debug = util.debuglog('timer'); const { destroyHooksExist, @@ -375,7 +375,7 @@ exports.enroll = util.deprecate(enroll, function setTimeout(callback, after, arg1, arg2, arg3) { if (typeof callback !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } var i, args; @@ -466,7 +466,7 @@ const clearTimeout = exports.clearTimeout = function(timer) { exports.setInterval = function(callback, repeat, arg1, arg2, arg3) { if (typeof callback !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } var i, args; @@ -739,7 +739,7 @@ const Immediate = class Immediate { function setImmediate(callback, arg1, arg2, arg3) { if (typeof callback !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } var i, args; diff --git a/lib/tls.js b/lib/tls.js index 96b6ec8d340e2f..5d7999f1fb61ad 100644 --- a/lib/tls.js +++ b/lib/tls.js @@ -21,7 +21,7 @@ 'use strict'; -const errors = require('internal/errors'); +const { ERR_TLS_CERT_ALTNAME_INVALID } = require('internal/errors').codes; const internalUtil = require('internal/util'); const internalTLS = require('internal/tls'); internalUtil.assertCrypto(); @@ -224,7 +224,7 @@ exports.checkServerIdentity = function checkServerIdentity(host, cert) { } if (!valid) { - const err = new errors.Error('ERR_TLS_CERT_ALTNAME_INVALID', reason); + const err = new ERR_TLS_CERT_ALTNAME_INVALID(reason); err.reason = reason; err.host = host; err.cert = cert; diff --git a/lib/tty.js b/lib/tty.js index 79e61e981b5a07..51ec1cf89810bd 100644 --- a/lib/tty.js +++ b/lib/tty.js @@ -25,6 +25,7 @@ const { inherits, _extend } = require('util'); const net = require('net'); const { TTY, isTTY } = process.binding('tty_wrap'); const errors = require('internal/errors'); +const { ERR_INVALID_FD } = errors.codes; const readline = require('readline'); const { release } = require('os'); @@ -43,7 +44,7 @@ function ReadStream(fd, options) { if (!(this instanceof ReadStream)) return new ReadStream(fd, options); if (fd >> 0 !== fd || fd < 0) - throw new errors.RangeError('ERR_INVALID_FD', fd); + throw new ERR_INVALID_FD(fd); const ctx = {}; const tty = new TTY(fd, true, ctx); @@ -75,7 +76,7 @@ function WriteStream(fd) { if (!(this instanceof WriteStream)) return new WriteStream(fd); if (fd >> 0 !== fd || fd < 0) - throw new errors.RangeError('ERR_INVALID_FD', fd); + throw new ERR_INVALID_FD(fd); const ctx = {}; const tty = new TTY(fd, false, ctx); diff --git a/lib/url.js b/lib/url.js index ab4b2b4647edd2..bb6637809adb70 100644 --- a/lib/url.js +++ b/lib/url.js @@ -26,7 +26,9 @@ const { toASCII } = process.binding('config').hasIntl ? const { hexTable } = require('internal/querystring'); -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE +} = require('internal/errors').codes; const { spliceOne } = require('internal/util'); @@ -103,7 +105,7 @@ function urlParse(url, parseQueryString, slashesDenoteHost) { Url.prototype.parse = function parse(url, parseQueryString, slashesDenoteHost) { if (typeof url !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'url', 'string', url); + throw new ERR_INVALID_ARG_TYPE('url', 'string', url); } // Copy chrome, IE, opera backslash-handling behavior. @@ -493,8 +495,8 @@ function urlFormat(urlObject, options) { if (typeof urlObject === 'string') { urlObject = urlParse(urlObject); } else if (typeof urlObject !== 'object' || urlObject === null) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'urlObject', - ['Object', 'string'], urlObject); + throw new ERR_INVALID_ARG_TYPE('urlObject', + ['Object', 'string'], urlObject); } else if (!(urlObject instanceof Url)) { var format = urlObject[formatSymbol]; return format ? diff --git a/lib/util.js b/lib/util.js index 888c005f2f60ef..70a76ccdcf813f 100644 --- a/lib/util.js +++ b/lib/util.js @@ -22,6 +22,11 @@ 'use strict'; const errors = require('internal/errors'); +const { + ERR_FALSY_VALUE_REJECTION, + ERR_INVALID_ARG_TYPE, + ERR_OUT_OF_RANGE +} = errors.codes; const { TextDecoder, TextEncoder } = require('internal/encoding'); const { isBuffer } = require('buffer').Buffer; @@ -317,7 +322,7 @@ Object.defineProperty(inspect, 'defaultOptions', { }, set(options) { if (options === null || typeof options !== 'object') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object'); + throw new ERR_INVALID_ARG_TYPE('options', 'Object'); } return _extend(inspectDefaultOptions, options); } @@ -1012,14 +1017,13 @@ function log() { function inherits(ctor, superCtor) { if (ctor === undefined || ctor === null) - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'ctor', 'Function'); + throw new ERR_INVALID_ARG_TYPE('ctor', 'Function'); if (superCtor === undefined || superCtor === null) - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'superCtor', 'Function'); + throw new ERR_INVALID_ARG_TYPE('superCtor', 'Function'); if (superCtor.prototype === undefined) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'superCtor.prototype', - 'Function'); + throw new ERR_INVALID_ARG_TYPE('superCtor.prototype', 'Function'); } ctor.super_ = superCtor; Object.setPrototypeOf(ctor.prototype, superCtor.prototype); @@ -1067,7 +1071,7 @@ function callbackifyOnRejected(reason, cb) { // occurred", we error-wrap so the callback consumer can distinguish between // "the promise rejected with null" or "the promise fulfilled with undefined". if (!reason) { - const newReason = new errors.Error('ERR_FALSY_VALUE_REJECTION'); + const newReason = new ERR_FALSY_VALUE_REJECTION(); newReason.reason = reason; reason = newReason; Error.captureStackTrace(reason, callbackifyOnRejected); @@ -1077,10 +1081,7 @@ function callbackifyOnRejected(reason, cb) { function callbackify(original) { if (typeof original !== 'function') { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', - 'original', - 'Function'); + throw new ERR_INVALID_ARG_TYPE('original', 'Function'); } // We DO NOT return the promise as it gives the user a false sense that @@ -1089,10 +1090,7 @@ function callbackify(original) { function callbackified(...args) { const maybeCb = args.pop(); if (typeof maybeCb !== 'function') { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', - 'last argument', - 'Function'); + throw new ERR_INVALID_ARG_TYPE('last argument', 'Function'); } const cb = (...args) => { Reflect.apply(maybeCb, this, args); }; // In true node style we process the callback on `nextTick` with all the @@ -1110,11 +1108,10 @@ function callbackify(original) { function getSystemErrorName(err) { if (typeof err !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'err', 'number', err); + throw new ERR_INVALID_ARG_TYPE('err', 'number', err); } if (err >= 0 || !Number.isSafeInteger(err)) { - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'err', - 'a negative integer', err); + throw new ERR_OUT_OF_RANGE('err', 'a negative integer', err); } return internalErrorName(err); } diff --git a/lib/v8.js b/lib/v8.js index fffd18bf1beb84..0e2a6533dc87cc 100644 --- a/lib/v8.js +++ b/lib/v8.js @@ -15,7 +15,7 @@ 'use strict'; const { Buffer } = require('buffer'); -const errors = require('internal/errors'); +const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes; const { Serializer: _Serializer, Deserializer: _Deserializer @@ -67,7 +67,7 @@ const heapSpaceStatisticsBuffer = function setFlagsFromString(flags) { if (typeof flags !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'flags', 'string'); + throw new ERR_INVALID_ARG_TYPE('flags', 'string'); _setFlagsFromString(flags); } diff --git a/lib/vm.js b/lib/vm.js index 78a2de16d38603..554aff8bfcc1b0 100644 --- a/lib/vm.js +++ b/lib/vm.js @@ -29,7 +29,7 @@ const { isContext, } = process.binding('contextify'); -const errors = require('internal/errors'); +const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes; // The binding provides a few useful primitives: // - Script(code, { filename = "evalmachine.anonymous", @@ -81,8 +81,7 @@ Script.prototype.runInNewContext = function(sandbox, options) { function validateString(prop, propName) { if (prop !== undefined && typeof prop !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', propName, - 'string', prop); + throw new ERR_INVALID_ARG_TYPE(propName, 'string', prop); } function getContextOptions(options) { @@ -108,8 +107,7 @@ function createContext(sandbox, options) { if (options !== undefined) { if (typeof options !== 'object' || options === null) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', - 'object', options); + throw new ERR_INVALID_ARG_TYPE('options', 'object', options); } options = { name: options.name, @@ -118,8 +116,7 @@ function createContext(sandbox, options) { if (options.name === undefined) { options.name = `VM Context ${defaultContextNameIndex++}`; } else if (typeof options.name !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.name', - 'string', options.name); + throw new ERR_INVALID_ARG_TYPE('options.name', 'string', options.name); } validateString(options.origin, 'options.origin'); } else { diff --git a/lib/zlib.js b/lib/zlib.js index 0fba957c09d371..93f878712add08 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -21,7 +21,13 @@ 'use strict'; -const errors = require('internal/errors'); +const { + ERR_BUFFER_TOO_LARGE, + ERR_INVALID_ARG_TYPE, + ERR_OUT_OF_RANGE, + ERR_ZLIB_BINDING_CLOSED, + ERR_ZLIB_INITIALIZATION_FAILED +} = require('internal/errors').codes; const Transform = require('_stream_transform'); const { _extend } = require('util'); const { isAnyArrayBuffer } = process.binding('util'); @@ -97,7 +103,7 @@ function zlibBufferOnEnd() { var buf; var err; if (this.nread >= kMaxLength) { - err = new errors.RangeError('ERR_BUFFER_TOO_LARGE'); + err = new ERR_BUFFER_TOO_LARGE(); } else if (this.nread === 0) { buf = Buffer.alloc(0); } else { @@ -120,10 +126,10 @@ function zlibBufferSync(engine, buffer) { if (isAnyArrayBuffer(buffer)) { buffer = Buffer.from(buffer); } else { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'buffer', - ['string', 'Buffer', 'TypedArray', 'DataView', - 'ArrayBuffer']); + throw new ERR_INVALID_ARG_TYPE( + 'buffer', + ['string', 'Buffer', 'TypedArray', 'DataView', 'ArrayBuffer'] + ); } } buffer = processChunkSync(engine, buffer, engine._finishFlushFlag); @@ -172,15 +178,13 @@ function checkFiniteNumber(number, name) { // Other non-numbers if (typeof number !== 'number') { - const err = new errors.TypeError('ERR_INVALID_ARG_TYPE', name, - 'number', number); + const err = new ERR_INVALID_ARG_TYPE(name, 'number', number); Error.captureStackTrace(err, checkFiniteNumber); throw err; } // Infinite numbers - const err = new errors.RangeError('ERR_OUT_OF_RANGE', name, - 'a finite number', number); + const err = new ERR_OUT_OF_RANGE(name, 'a finite number', number); Error.captureStackTrace(err, checkFiniteNumber); throw err; } @@ -194,8 +198,8 @@ function checkRangesOrGetDefault(number, name, lower, upper, def) { return def; } if (number < lower || number > upper) { - const err = new errors.RangeError('ERR_OUT_OF_RANGE', name, - `>= ${lower} and <= ${upper}`, number); + const err = new ERR_OUT_OF_RANGE(name, + `>= ${lower} and <= ${upper}`, number); Error.captureStackTrace(err, checkRangesOrGetDefault); throw err; } @@ -226,8 +230,8 @@ function Zlib(opts, mode) { if (!checkFiniteNumber(chunkSize, 'options.chunkSize')) { chunkSize = Z_DEFAULT_CHUNK; } else if (chunkSize < Z_MIN_CHUNK) { - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'options.chunkSize', - `>= ${Z_MIN_CHUNK}`, chunkSize); + throw new ERR_OUT_OF_RANGE('options.chunkSize', + `>= ${Z_MIN_CHUNK}`, chunkSize); } flush = checkRangesOrGetDefault( @@ -259,10 +263,11 @@ function Zlib(opts, mode) { if (isAnyArrayBuffer(dictionary)) { dictionary = Buffer.from(dictionary); } else { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'options.dictionary', + throw new ERR_INVALID_ARG_TYPE( + 'options.dictionary', ['Buffer', 'TypedArray', 'DataView', 'ArrayBuffer'], - dictionary); + dictionary + ); } } @@ -288,7 +293,7 @@ function Zlib(opts, mode) { this._writeState, processCallback, dictionary)) { - throw new errors.Error('ERR_ZLIB_INITIALIZATION_FAILED'); + throw new ERR_ZLIB_INITIALIZATION_FAILED(); } this._outBuffer = Buffer.allocUnsafe(chunkSize); @@ -491,7 +496,7 @@ function processChunkSync(self, chunk, flushFlag) { if (nread >= kMaxLength) { _close(self); - throw new errors.RangeError('ERR_BUFFER_TOO_LARGE'); + throw new ERR_BUFFER_TOO_LARGE(); } _close(self); @@ -505,7 +510,7 @@ function processChunkSync(self, chunk, flushFlag) { function processChunk(self, chunk, flushFlag, cb) { var handle = self._handle; if (!handle) - return cb(new errors.Error('ERR_ZLIB_BINDING_CLOSED')); + return cb(new ERR_ZLIB_BINDING_CLOSED()); handle.buffer = chunk; handle.cb = cb; diff --git a/test/parallel/test-child-process-spawnsync-validation-errors.js b/test/parallel/test-child-process-spawnsync-validation-errors.js index 433e0fce167366..802acad1031374 100644 --- a/test/parallel/test-child-process-spawnsync-validation-errors.js +++ b/test/parallel/test-child-process-spawnsync-validation-errors.js @@ -8,10 +8,10 @@ let invalidArgTypeError; if (common.isWindows) { invalidArgTypeError = - common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError }, 36); + common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError }, 42); } else { invalidArgTypeError = - common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError }, 56); + common.expectsError({ code: 'ERR_INVALID_ARG_TYPE', type: TypeError }, 62); } const invalidRangeError = @@ -127,18 +127,16 @@ if (!common.isWindows) { { // Validate the windowsHide option - const err = /^TypeError: "windowsHide" must be a boolean$/; - pass('windowsHide', undefined); pass('windowsHide', null); pass('windowsHide', true); pass('windowsHide', false); - fail('windowsHide', 0, err); - fail('windowsHide', 1, err); - fail('windowsHide', __dirname, err); - fail('windowsHide', [], err); - fail('windowsHide', {}, err); - fail('windowsHide', common.mustNotCall(), err); + fail('windowsHide', 0, invalidArgTypeError); + fail('windowsHide', 1, invalidArgTypeError); + fail('windowsHide', __dirname, invalidArgTypeError); + fail('windowsHide', [], invalidArgTypeError); + fail('windowsHide', {}, invalidArgTypeError); + fail('windowsHide', common.mustNotCall(), invalidArgTypeError); } { diff --git a/test/parallel/test-module-loading-error.js b/test/parallel/test-module-loading-error.js index 811d7d5ded8576..86932bd759d20c 100644 --- a/test/parallel/test-module-loading-error.js +++ b/test/parallel/test-module-loading-error.js @@ -74,7 +74,7 @@ const re = /^The "id" argument must be of type string\. Received type \w+$/; common.expectsError( () => { require(''); }, { - type: Error, + type: TypeError, code: 'ERR_INVALID_ARG_VALUE', message: 'The argument \'id\' must be a non-empty string. Received \'\'' }); diff --git a/test/parallel/test-net-server-listen-options.js b/test/parallel/test-net-server-listen-options.js index 83984844388a82..4f7a6bd28f561a 100644 --- a/test/parallel/test-net-server-listen-options.js +++ b/test/parallel/test-net-server-listen-options.js @@ -60,7 +60,7 @@ const listenOnPort = [ common.expectsError(block, { code: 'ERR_INVALID_OPT_VALUE', - type: Error, + type: TypeError, message: /^The value "{.*}" is invalid for option "options"$/ }); }