diff --git a/lib/_http_client.js b/lib/_http_client.js index 7bf485b47e60aa..3687288ee896e1 100644 --- a/lib/_http_client.js +++ b/lib/_http_client.js @@ -39,15 +39,23 @@ const { Buffer } = require('buffer'); const { urlToOptions, searchParamsSymbol } = require('internal/url'); const { outHeadersKey, ondrain } = require('internal/http'); const { nextTick } = require('internal/process/next_tick'); -const errors = require('internal/errors'); +const { + ERR_HTTP_HEADERS_SENT, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_DOMAIN_NAME, + ERR_INVALID_HTTP_TOKEN, + ERR_INVALID_PROTOCOL, + ERR_UNESCAPED_CHARACTERS +} = require('internal/errors').codes; const { validateTimerDuration } = require('internal/timers'); const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/; function validateHost(host, name) { if (host !== null && host !== undefined && typeof host !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', `options.${name}`, - ['string', 'undefined', 'null'], host); + throw new ERR_INVALID_ARG_TYPE(`options.${name}`, + ['string', 'undefined', 'null'], + host); } return host; } @@ -58,7 +66,7 @@ function ClientRequest(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]) { @@ -79,8 +87,8 @@ function ClientRequest(options, cb) { // Explicitly pass through this statement as agent will not be used // when createConnection is provided. } else if (typeof agent.addRequest !== 'function') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'Agent option', - ['Agent-like Object', 'undefined', 'false']); + throw new ERR_INVALID_ARG_TYPE('Agent option', + ['Agent-like Object', 'undefined', 'false']); } this.agent = agent; @@ -93,11 +101,11 @@ function ClientRequest(options, cb) { if (options.path) { path = String(options.path); if (INVALID_PATH_REGEX.test(path)) - throw new errors.TypeError('ERR_UNESCAPED_CHARACTERS', 'Request path'); + throw new ERR_UNESCAPED_CHARACTERS('Request path'); } if (protocol !== expectedProtocol) { - throw new errors.Error('ERR_INVALID_PROTOCOL', protocol, expectedProtocol); + throw new ERR_INVALID_PROTOCOL(protocol, expectedProtocol); } var defaultPort = options.defaultPort || @@ -115,13 +123,12 @@ function ClientRequest(options, cb) { var method = options.method; var methodIsString = (typeof method === 'string'); if (method !== null && method !== undefined && !methodIsString) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'method', - 'string', method); + throw new ERR_INVALID_ARG_TYPE('method', 'string', method); } if (methodIsString && method) { if (!checkIsHttpToken(method)) { - throw new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Method', method); + throw new ERR_INVALID_HTTP_TOKEN('Method', method); } method = this.method = method.toUpperCase(); } else { @@ -203,7 +210,7 @@ function ClientRequest(options, cb) { if (this.getHeader('expect')) { if (this._header) { - throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'render'); + throw new ERR_HTTP_HEADERS_SENT('render'); } this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n', @@ -261,7 +268,7 @@ ClientRequest.prototype._finish = function _finish() { ClientRequest.prototype._implicitHeader = function _implicitHeader() { if (this._header) { - throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'render'); + throw new ERR_HTTP_HEADERS_SENT('render'); } this._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n', this[outHeadersKey]); diff --git a/lib/_http_outgoing.js b/lib/_http_outgoing.js index 985b74679c0027..cd7caae9ae735e 100644 --- a/lib/_http_outgoing.js +++ b/lib/_http_outgoing.js @@ -33,7 +33,17 @@ const checkInvalidHeaderChar = common._checkInvalidHeaderChar; const { outHeadersKey } = require('internal/http'); const { async_id_symbol } = require('internal/async_hooks').symbols; const { nextTick } = require('internal/process/next_tick'); -const errors = require('internal/errors'); +const { + ERR_HTTP_HEADERS_SENT, + ERR_HTTP_INVALID_HEADER_VALUE, + ERR_HTTP_TRAILER_INVALID, + ERR_INVALID_HTTP_TOKEN, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CHAR, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_WRITE_AFTER_END +} = require('internal/errors').codes; const { CRLF, debug } = common; const { utcDate } = internalHttp; @@ -165,7 +175,7 @@ Object.defineProperty(OutgoingMessage.prototype, '_headerNames', { OutgoingMessage.prototype._renderHeaders = function _renderHeaders() { if (this._header) { - throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'render'); + throw new ERR_HTTP_HEADERS_SENT('render'); } var headersMap = this[outHeadersKey]; @@ -424,7 +434,7 @@ function _storeHeader(firstLine, headers) { // header fields, regardless of the header fields present in the // message, and thus cannot contain a message body or 'trailers'. if (this.chunkedEncoding !== true && state.trailer) { - throw new errors.Error('ERR_HTTP_TRAILER_INVALID'); + throw new ERR_HTTP_TRAILER_INVALID(); } this._header = state.header + CRLF; @@ -488,12 +498,12 @@ function matchHeader(self, state, field, value) { function validateHeader(name, value) { let err; if (typeof name !== 'string' || !name || !checkIsHttpToken(name)) { - err = new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Header name', name); + err = new ERR_INVALID_HTTP_TOKEN('Header name', name); } else if (value === undefined) { - err = new errors.TypeError('ERR_HTTP_INVALID_HEADER_VALUE', value, name); + err = new ERR_HTTP_INVALID_HEADER_VALUE(value, name); } else if (checkInvalidHeaderChar(value)) { debug('Header "%s" contains invalid characters', name); - err = new errors.TypeError('ERR_INVALID_CHAR', 'header content', name); + err = new ERR_INVALID_CHAR('header content', name); } if (err !== undefined) { Error.captureStackTrace(err, validateHeader); @@ -503,7 +513,7 @@ function validateHeader(name, value) { OutgoingMessage.prototype.setHeader = function setHeader(name, value) { if (this._header) { - throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'set'); + throw new ERR_HTTP_HEADERS_SENT('set'); } validateHeader(name, value); @@ -529,7 +539,7 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) { OutgoingMessage.prototype.getHeader = function getHeader(name) { if (typeof name !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + throw new ERR_INVALID_ARG_TYPE('name', 'string'); } if (!this[outHeadersKey]) return; @@ -565,7 +575,7 @@ OutgoingMessage.prototype.getHeaders = function getHeaders() { OutgoingMessage.prototype.hasHeader = function hasHeader(name) { if (typeof name !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + throw new ERR_INVALID_ARG_TYPE('name', 'string'); } return !!(this[outHeadersKey] && this[outHeadersKey][name.toLowerCase()]); @@ -574,11 +584,11 @@ OutgoingMessage.prototype.hasHeader = function hasHeader(name) { OutgoingMessage.prototype.removeHeader = function removeHeader(name) { if (typeof name !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + throw new ERR_INVALID_ARG_TYPE('name', 'string'); } if (this._header) { - throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'remove'); + throw new ERR_HTTP_HEADERS_SENT('remove'); } var key = name.toLowerCase(); @@ -605,7 +615,7 @@ OutgoingMessage.prototype.removeHeader = function removeHeader(name) { OutgoingMessage.prototype._implicitHeader = function _implicitHeader() { - throw new errors.Error('ERR_METHOD_NOT_IMPLEMENTED', '_implicitHeader()'); + throw new ERR_METHOD_NOT_IMPLEMENTED('_implicitHeader()'); }; Object.defineProperty(OutgoingMessage.prototype, 'headersSent', { @@ -622,7 +632,7 @@ OutgoingMessage.prototype.write = function write(chunk, encoding, callback) { function write_(msg, chunk, encoding, callback, fromEnd) { if (msg.finished) { - const err = new errors.Error('ERR_STREAM_WRITE_AFTER_END'); + const err = new ERR_STREAM_WRITE_AFTER_END(); nextTick(msg.socket && msg.socket[async_id_symbol], writeAfterEndNT.bind(msg), err, @@ -642,8 +652,7 @@ function write_(msg, chunk, encoding, callback, fromEnd) { } if (!fromEnd && typeof chunk !== 'string' && !(chunk instanceof Buffer)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument', - ['string', 'Buffer']); + throw new ERR_INVALID_ARG_TYPE('first argument', ['string', 'Buffer']); } @@ -711,12 +720,11 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) { value = headers[key]; } if (typeof field !== 'string' || !field || !checkIsHttpToken(field)) { - throw new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Trailer name', - field); + throw new ERR_INVALID_HTTP_TOKEN('Trailer name', field); } if (checkInvalidHeaderChar(value)) { debug('Trailer "%s" contains invalid characters', field); - throw new errors.TypeError('ERR_INVALID_CHAR', 'trailer content', field); + throw new ERR_INVALID_CHAR('trailer content', field); } this._trailer += field + ': ' + escapeHeaderValue(value) + CRLF; } @@ -742,8 +750,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) { var uncork; if (chunk) { if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument', - ['string', 'Buffer']); + throw new ERR_INVALID_ARG_TYPE('first argument', ['string', 'Buffer']); } if (!this._header) { if (typeof chunk === 'string') @@ -874,7 +881,7 @@ OutgoingMessage.prototype.flush = internalUtil.deprecate(function() { OutgoingMessage.prototype.pipe = function pipe() { // OutgoingMessage should be write-only. Piping from it is disabled. - this.emit('error', new errors.Error('ERR_STREAM_CANNOT_PIPE')); + this.emit('error', new ERR_STREAM_CANNOT_PIPE()); }; module.exports = { diff --git a/lib/_http_server.js b/lib/_http_server.js index 1b9b4677d50ba2..498800dd1ee445 100644 --- a/lib/_http_server.js +++ b/lib/_http_server.js @@ -43,7 +43,11 @@ const { getOrSetAsyncId } = require('internal/async_hooks'); const { IncomingMessage } = require('_http_incoming'); -const errors = require('internal/errors'); +const { + ERR_HTTP_HEADERS_SENT, + ERR_HTTP_INVALID_STATUS_CODE, + ERR_INVALID_CHAR +} = require('internal/errors').codes; const Buffer = require('buffer').Buffer; const kServerResponse = Symbol('ServerResponse'); @@ -201,8 +205,7 @@ function writeHead(statusCode, reason, obj) { statusCode |= 0; if (statusCode < 100 || statusCode > 999) { - throw new errors.RangeError('ERR_HTTP_INVALID_STATUS_CODE', - originalStatusCode); + throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode); } @@ -229,7 +232,7 @@ function writeHead(statusCode, reason, obj) { } } if (k === undefined && this._header) { - throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'render'); + throw new ERR_HTTP_HEADERS_SENT('render'); } // only progressive api is used headers = this[outHeadersKey]; @@ -239,7 +242,7 @@ function writeHead(statusCode, reason, obj) { } if (checkInvalidHeaderChar(this.statusMessage)) - throw new errors.Error('ERR_INVALID_CHAR', 'statusMessage'); + throw new ERR_INVALID_CHAR('statusMessage'); var statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}${CRLF}`; diff --git a/lib/_stream_readable.js b/lib/_stream_readable.js index 5781dfd471e72d..f49da5086519a5 100644 --- a/lib/_stream_readable.js +++ b/lib/_stream_readable.js @@ -32,7 +32,12 @@ const debug = util.debuglog('stream'); const BufferList = require('internal/streams/BufferList'); const destroyImpl = require('internal/streams/destroy'); const { getHighWaterMark } = require('internal/streams/state'); -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_STREAM_PUSH_AFTER_EOF, + ERR_STREAM_READ_NOT_IMPLEMENTED, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT +} = require('internal/errors').codes; const ReadableAsyncIterator = require('internal/streams/async_iterator'); const { emitExperimentalWarning } = require('internal/util'); var StringDecoder; @@ -232,12 +237,11 @@ function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { if (addToFront) { if (state.endEmitted) - stream.emit('error', - new errors.Error('ERR_STREAM_UNSHIFT_AFTER_END_EVENT')); + stream.emit('error', new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); else addChunk(stream, state, chunk, true); } else if (state.ended) { - stream.emit('error', new errors.Error('ERR_STREAM_PUSH_AFTER_EOF')); + stream.emit('error', new ERR_STREAM_PUSH_AFTER_EOF()); } else if (state.destroyed) { return false; } else { @@ -285,8 +289,7 @@ function chunkInvalid(state, chunk) { typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'chunk', ['string', 'Buffer', 'Uint8Array']); + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array']); } return er; } @@ -565,7 +568,7 @@ function maybeReadMore_(stream, state) { // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function(n) { - this.emit('error', new errors.Error('ERR_STREAM_READ_NOT_IMPLEMENTED')); + this.emit('error', new ERR_STREAM_READ_NOT_IMPLEMENTED()); }; Readable.prototype.pipe = function(dest, pipeOpts) { diff --git a/lib/_stream_transform.js b/lib/_stream_transform.js index b82114ecaecd1d..387a39318cdc2f 100644 --- a/lib/_stream_transform.js +++ b/lib/_stream_transform.js @@ -64,7 +64,12 @@ 'use strict'; module.exports = Transform; -const errors = require('internal/errors'); +const { + ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK, + ERR_TRANSFORM_ALREADY_TRANSFORMING, + ERR_TRANSFORM_WITH_LENGTH_0 +} = require('internal/errors').codes; const Duplex = require('_stream_duplex'); const util = require('util'); util.inherits(Transform, Duplex); @@ -77,7 +82,7 @@ function afterTransform(er, data) { var cb = ts.writecb; if (cb === null) { - return this.emit('error', new errors.Error('ERR_MULTIPLE_CALLBACK')); + return this.emit('error', new ERR_MULTIPLE_CALLBACK()); } ts.writechunk = null; @@ -157,7 +162,7 @@ Transform.prototype.push = function(chunk, encoding) { // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function(chunk, encoding, cb) { - throw new errors.Error('ERR_METHOD_NOT_IMPLEMENTED', '_transform'); + throw new ERR_METHOD_NOT_IMPLEMENTED('_transform'); }; Transform.prototype._write = function(chunk, encoding, cb) { @@ -209,9 +214,9 @@ function done(stream, er, data) { // if there's nothing in the write buffer, then that means // that nothing more will ever be provided if (stream._writableState.length) - throw new errors.Error('ERR_TRANSFORM_WITH_LENGTH_0'); + throw new ERR_TRANSFORM_WITH_LENGTH_0(); if (stream._transformState.transforming) - throw new errors.Error('ERR_TRANSFORM_ALREADY_TRANSFORMING'); + throw new ERR_TRANSFORM_ALREADY_TRANSFORMING(); return stream.push(null); } diff --git a/lib/_stream_writable.js b/lib/_stream_writable.js index d5cfe07f171324..aa29779e443d2b 100644 --- a/lib/_stream_writable.js +++ b/lib/_stream_writable.js @@ -34,7 +34,15 @@ const Stream = require('stream'); const { Buffer } = require('buffer'); const destroyImpl = require('internal/streams/destroy'); const { getHighWaterMark } = require('internal/streams/state'); -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED, + ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING +} = require('internal/errors').codes; util.inherits(Writable, Stream); @@ -222,12 +230,12 @@ function Writable(options) { // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function() { - this.emit('error', new errors.Error('ERR_STREAM_CANNOT_PIPE')); + this.emit('error', new ERR_STREAM_CANNOT_PIPE()); }; function writeAfterEnd(stream, cb) { - var er = new errors.Error('ERR_STREAM_WRITE_AFTER_END'); + var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); process.nextTick(cb, er); @@ -241,10 +249,9 @@ function validChunk(stream, state, chunk, cb) { var er = false; if (chunk === null) { - er = new errors.TypeError('ERR_STREAM_NULL_VALUES'); + er = new ERR_STREAM_NULL_VALUES(); } else if (typeof chunk !== 'string' && !state.objectMode) { - er = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'chunk', - ['string', 'Buffer']); + er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer']); } if (er) { stream.emit('error', er); @@ -311,7 +318,7 @@ Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!Buffer.isEncoding(encoding)) - throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding); + throw new ERR_UNKNOWN_ENCODING(encoding); this._writableState.defaultEncoding = encoding; return this; }; @@ -394,7 +401,7 @@ function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writing = true; state.sync = true; if (state.destroyed) - state.onwrite(new errors.Error('ERR_STREAM_DESTROYED', 'write')); + state.onwrite(new ERR_STREAM_DESTROYED('write')); else if (writev) stream._writev(chunk, state.onwrite); else @@ -546,7 +553,7 @@ function clearBuffer(stream, state) { } Writable.prototype._write = function(chunk, encoding, cb) { - cb(new errors.Error('ERR_METHOD_NOT_IMPLEMENTED', '_write')); + cb(new ERR_METHOD_NOT_IMPLEMENTED('_write')); }; Writable.prototype._writev = null; diff --git a/lib/_tls_common.js b/lib/_tls_common.js index fcb6de81669e23..f63acad8ad174e 100644 --- a/lib/_tls_common.js +++ b/lib/_tls_common.js @@ -24,7 +24,10 @@ const { parseCertString } = require('internal/tls'); const { isArrayBufferView } = require('internal/util/types'); const tls = require('tls'); -const errors = require('internal/errors'); +const { + ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED, + ERR_INVALID_ARG_TYPE +} = require('internal/errors').codes; const { SSL_OP_CIPHER_SERVER_PREFERENCE } = process.binding('constants').crypto; @@ -56,8 +59,8 @@ function SecureContext(secureProtocol, secureOptions, context) { function validateKeyCert(value, type) { if (typeof value !== 'string' && !isArrayBufferView(value)) - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', type, + throw new ERR_INVALID_ARG_TYPE( + type, ['string', 'Buffer', 'TypedArray', 'DataView'] ); } @@ -212,12 +215,11 @@ exports.createSecureContext = function createSecureContext(options, context) { if (c.context.setClientCertEngine) c.context.setClientCertEngine(options.clientCertEngine); else - throw new errors.Error('ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED'); + throw new ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED(); } else if (options.clientCertEngine != null) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options.clientCertEngine', - ['string', 'null', 'undefined'], - options.clientCertEngine); + throw new ERR_INVALID_ARG_TYPE('options.clientCertEngine', + ['string', 'null', 'undefined'], + options.clientCertEngine); } return c; diff --git a/lib/_tls_wrap.js b/lib/_tls_wrap.js index c4725642707180..79646ba3d2bc73 100644 --- a/lib/_tls_wrap.js +++ b/lib/_tls_wrap.js @@ -38,7 +38,18 @@ const { Pipe, constants: PipeConstants } = process.binding('pipe_wrap'); const { SecureContext: NativeSecureContext } = process.binding('crypto'); -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_MULTIPLE_CALLBACK, + ERR_SOCKET_CLOSED, + ERR_TLS_DH_PARAM_SIZE, + ERR_TLS_HANDSHAKE_TIMEOUT, + ERR_TLS_RENEGOTIATE, + ERR_TLS_RENEGOTIATION_DISABLED, + ERR_TLS_REQUIRED_SERVER_NAME, + ERR_TLS_SESSION_ATTACK, + ERR_TLS_SNI_FROM_SERVER +} = require('internal/errors').codes; const kConnectOptions = Symbol('connect-options'); const kDisableRenegotiation = Symbol('disable-renegotiation'); const kErrorEmitted = Symbol('error-emitted'); @@ -71,12 +82,12 @@ function onhandshakestart(now) { } if (owner[kDisableRenegotiation] && this.handshakes > 0) { - owner._emitTLSError(new errors.Error('ERR_TLS_RENEGOTIATION_DISABLED')); + owner._emitTLSError(new ERR_TLS_RENEGOTIATION_DISABLED()); } } function emitSessionAttackError(socket) { - socket._emitTLSError(new errors.Error('ERR_TLS_SESSION_ATTACK')); + socket._emitTLSError(new ERR_TLS_SESSION_ATTACK()); } function onhandshakedone() { @@ -100,14 +111,14 @@ function loadSession(hello) { var once = false; function onSession(err, session) { if (once) - return owner.destroy(new errors.Error('ERR_MULTIPLE_CALLBACK')); + return owner.destroy(new ERR_MULTIPLE_CALLBACK()); once = true; if (err) return owner.destroy(err); if (owner._handle === null) - return owner.destroy(new errors.Error('ERR_SOCKET_CLOSED')); + return owner.destroy(new ERR_SOCKET_CLOSED()); owner._handle.loadSession(session); owner._handle.endParser(); @@ -131,14 +142,14 @@ function loadSNI(info) { let once = false; owner._SNICallback(servername, (err, context) => { if (once) - return owner.destroy(new errors.Error('ERR_MULTIPLE_CALLBACK')); + return owner.destroy(new ERR_MULTIPLE_CALLBACK()); once = true; if (err) return owner.destroy(err); if (owner._handle === null) - return owner.destroy(new errors.Error('ERR_SOCKET_CLOSED')); + return owner.destroy(new ERR_SOCKET_CLOSED()); // TODO(indutny): eventually disallow raw `SecureContext` if (context) @@ -175,14 +186,14 @@ function requestOCSP(socket, info) { let once = false; const onOCSP = (err, response) => { if (once) - return socket.destroy(new errors.Error('ERR_MULTIPLE_CALLBACK')); + return socket.destroy(new ERR_MULTIPLE_CALLBACK()); once = true; if (err) return socket.destroy(err); if (socket._handle === null) - return socket.destroy(new errors.Error('ERR_SOCKET_CLOSED')); + return socket.destroy(new ERR_SOCKET_CLOSED()); if (response) socket._handle.setOCSPResponse(response); @@ -217,7 +228,7 @@ function onnewsession(key, session) { once = true; if (owner._handle === null) - return owner.destroy(new errors.Error('ERR_SOCKET_CLOSED')); + return owner.destroy(new ERR_SOCKET_CLOSED()); this.newSessionDone(); @@ -570,7 +581,7 @@ TLSSocket.prototype.renegotiate = function(options, callback) { } if (!this._handle.renegotiate()) { if (callback) { - process.nextTick(callback, new errors.Error('ERR_TLS_RENEGOTIATE')); + process.nextTick(callback, new ERR_TLS_RENEGOTIATE()); } return false; } @@ -594,7 +605,7 @@ TLSSocket.prototype.getTLSTicket = function getTLSTicket() { }; TLSSocket.prototype._handleTimeout = function() { - this._emitTLSError(new errors.Error('ERR_TLS_HANDSHAKE_TIMEOUT')); + this._emitTLSError(new ERR_TLS_HANDSHAKE_TIMEOUT()); }; TLSSocket.prototype._emitTLSError = function(err) { @@ -656,11 +667,11 @@ TLSSocket.prototype._start = function() { TLSSocket.prototype.setServername = function(name) { if (typeof name !== 'string') { - throw new errors.Error('ERR_INVALID_ARG_TYPE', 'name', 'string'); + throw new ERR_INVALID_ARG_TYPE('name', 'string'); } if (this._tlsOptions.isServer) { - throw new errors.Error('ERR_TLS_SNI_FROM_SERVER'); + throw new ERR_TLS_SNI_FROM_SERVER(); } this._handle.setServername(name); @@ -855,7 +866,7 @@ function Server(options, listener) { } else if (options == null || typeof options === 'object') { options = options || {}; } else { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object'); + throw new ERR_INVALID_ARG_TYPE('options', 'Object'); } @@ -886,7 +897,7 @@ function Server(options, listener) { this[kSNICallback] = options.SNICallback; if (typeof this[kHandshakeTimeout] !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'timeout', 'number'); + throw new ERR_INVALID_ARG_TYPE('timeout', 'number'); } if (this.sessionTimeout) { @@ -975,7 +986,7 @@ Server.prototype.setOptions = function(options) { // SNI Contexts High-Level API Server.prototype.addContext = function(servername, context) { if (!servername) { - throw new errors.Error('ERR_TLS_REQUIRED_SERVER_NAME'); + throw new ERR_TLS_REQUIRED_SERVER_NAME(); } var re = new RegExp('^' + @@ -1040,7 +1051,7 @@ function onConnectSecure() { // specified in options. const ekeyinfo = this.getEphemeralKeyInfo(); if (ekeyinfo.type === 'DH' && ekeyinfo.size < options.minDHSize) { - const err = new errors.Error('ERR_TLS_DH_PARAM_SIZE', ekeyinfo.size); + const err = new ERR_TLS_DH_PARAM_SIZE(ekeyinfo.size); this.emit('error', err); this.destroy(); return; diff --git a/lib/fs/promises.js b/lib/fs/promises.js index 8cbcd963c772c8..2252900e22aaf0 100644 --- a/lib/fs/promises.js +++ b/lib/fs/promises.js @@ -12,7 +12,12 @@ const { } = process.binding('constants').fs; const binding = process.binding('fs'); const { Buffer, kMaxLength } = require('buffer'); -const errors = require('internal/errors'); +const { + ERR_BUFFER_TOO_LARGE, + ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_OUT_OF_RANGE +} = require('internal/errors').codes; const { getPathFromURL } = require('internal/url'); const { isUint8Array } = require('internal/util/types'); const { @@ -107,8 +112,7 @@ class FileHandle { function validateFileHandle(handle) { if (!(handle instanceof FileHandle)) - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'filehandle', 'FileHandle'); + throw new ERR_INVALID_ARG_TYPE('filehandle', 'FileHandle'); } async function writeFileHandle(filehandle, data, options) { @@ -139,7 +143,7 @@ async function readFileHandle(filehandle, options) { return Buffer.alloc(0); if (size > kMaxLength) - throw new errors.RangeError('ERR_BUFFER_TOO_LARGE'); + throw new ERR_BUFFER_TOO_LARGE(); const chunks = []; const chunkSize = Math.min(size, 16384); @@ -361,7 +365,7 @@ async function fchmod(handle, mode) { validateFileHandle(handle); validateUint32(mode, 'mode'); if (mode < 0 || mode > 0o777) - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'mode'); + throw new ERR_OUT_OF_RANGE('mode'); return binding.fchmod(handle.fd, mode, kUsePromises); } @@ -379,7 +383,7 @@ async function lchmod(path, mode) { O_WRONLY | O_SYMLINK); return fchmod(fd, mode).finally(fd.close.bind(fd)); } - throw new errors.Error('ERR_METHOD_NOT_IMPLEMENTED'); + throw new ERR_METHOD_NOT_IMPLEMENTED(); } async function lchown(path, uid, gid) { @@ -388,7 +392,7 @@ async function lchown(path, uid, gid) { O_WRONLY | O_SYMLINK); return fchmod(fd, uid, gid).finally(fd.close.bind(fd)); } - throw new errors.Error('ERR_METHOD_NOT_IMPLEMENTED'); + throw new ERR_METHOD_NOT_IMPLEMENTED(); } async function fchown(handle, uid, gid) { @@ -433,10 +437,7 @@ async function realpath(path, options) { async function mkdtemp(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); return binding.mkdtemp(`${prefix}XXXXXX`, options.encoding, kUsePromises); diff --git a/lib/internal/async_hooks.js b/lib/internal/async_hooks.js index 44be2990d6a5d8..72d74243d8cae5 100644 --- a/lib/internal/async_hooks.js +++ b/lib/internal/async_hooks.js @@ -1,6 +1,9 @@ 'use strict'; -const errors = require('internal/errors'); +const { + ERR_ASYNC_TYPE, + ERR_INVALID_ASYNC_ID +} = require('internal/errors').codes; const async_wrap = process.binding('async_wrap'); /* async_hook_fields is a Uint32Array wrapping the uint32_t array of * Environment::AsyncHooks::fields_[]. Each index tracks the number of active @@ -115,7 +118,7 @@ function validateAsyncId(asyncId, type) { if (async_hook_fields[kCheck] <= 0) return; if (!Number.isSafeInteger(asyncId) || asyncId < -1) { - fatalError(new errors.RangeError('ERR_INVALID_ASYNC_ID', type, asyncId)); + fatalError(new ERR_INVALID_ASYNC_ID(type, asyncId)); } } @@ -313,7 +316,7 @@ function emitInitScript(asyncId, type, triggerAsyncId, resource) { validateAsyncId(triggerAsyncId, 'triggerAsyncId'); if (async_hook_fields[kCheck] > 0 && (typeof type !== 'string' || type.length <= 0)) { - throw new errors.TypeError('ERR_ASYNC_TYPE', type); + throw new ERR_ASYNC_TYPE(type); } // Short circuit all checks for the common case. Which is that no hooks have diff --git a/lib/internal/buffer.js b/lib/internal/buffer.js index b5da69a5b3e27b..fe10b20c80541b 100644 --- a/lib/internal/buffer.js +++ b/lib/internal/buffer.js @@ -1,7 +1,11 @@ 'use strict'; const binding = process.binding('buffer'); -const { TypeError, RangeError } = require('internal/errors'); +const { + ERR_BUFFER_OUT_OF_BOUNDS, + ERR_INVALID_ARG_TYPE, + ERR_OUT_OF_RANGE +} = require('internal/errors').codes; const { setupBufferJS } = binding; // Remove from the binding so that function is only available as exported here. @@ -26,33 +30,29 @@ function checkBounds(buf, offset, byteLength) { function checkInt(value, min, max, buf, offset, byteLength) { if (value > max || value < min) { - throw new RangeError('ERR_OUT_OF_RANGE', - 'value', `>= ${min} and <= ${max}`, value); + throw new ERR_OUT_OF_RANGE('value', `>= ${min} and <= ${max}`, value); } checkBounds(buf, offset, byteLength); } function checkNumberType(value, type) { if (typeof value !== 'number') { - throw new TypeError('ERR_INVALID_ARG_TYPE', - type || 'offset', 'number', value); + throw new ERR_INVALID_ARG_TYPE(type || 'offset', 'number', value); } } function boundsError(value, length, type) { if (Math.floor(value) !== value) { checkNumberType(value, type); - throw new RangeError('ERR_OUT_OF_RANGE', - type || 'offset', 'an integer', value); + throw new ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value); } if (length < 0) - throw new RangeError('ERR_BUFFER_OUT_OF_BOUNDS', null, true); + throw new ERR_BUFFER_OUT_OF_BOUNDS(null, true); - throw new RangeError('ERR_OUT_OF_RANGE', - type || 'offset', - `>= ${type ? 1 : 0} and <= ${length}`, - value); + throw new ERR_OUT_OF_RANGE(type || 'offset', + `>= ${type ? 1 : 0} and <= ${length}`, + value); } // Read integers. @@ -545,9 +545,7 @@ function writeU_Int8(buf, value, offset, min, max) { // `checkInt()` can not be used here because it checks two entries. checkNumberType(offset); if (value > max || value < min) { - throw new RangeError('ERR_OUT_OF_RANGE', - 'value', - `>= ${min} and <= ${max}`, value); + throw new ERR_OUT_OF_RANGE('value', `>= ${min} and <= ${max}`, value); } if (buf[offset] === undefined) boundsError(offset, buf.length - 1); diff --git a/lib/internal/child_process.js b/lib/internal/child_process.js index 58bb46e8a27a0e..3c8a314bf04644 100644 --- a/lib/internal/child_process.js +++ b/lib/internal/child_process.js @@ -1,6 +1,19 @@ 'use strict'; -const errors = require('internal/errors'); +const { + errnoException, + codes: { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_HANDLE_TYPE, + ERR_INVALID_OPT_VALUE, + ERR_INVALID_SYNC_FORK_INPUT, + ERR_IPC_CHANNEL_CLOSED, + ERR_IPC_DISCONNECTED, + ERR_IPC_ONE_PIPE, + ERR_IPC_SYNC_FORK, + ERR_MISSING_ARGS + } +} = require('internal/errors'); const { StringDecoder } = require('string_decoder'); const EventEmitter = require('events'); const net = require('net'); @@ -29,7 +42,6 @@ const { UV_ESRCH } = process.binding('uv'); -const errnoException = errors.errnoException; const { SocketListSend, SocketListReceive } = SocketList; const MAX_HANDLE_RETRANSMISSIONS = 3; @@ -263,8 +275,7 @@ ChildProcess.prototype.spawn = function(options) { var i; 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); } // If no `stdio` option was given - use default @@ -281,16 +292,16 @@ ChildProcess.prototype.spawn = function(options) { if (options.envPairs === undefined) options.envPairs = []; else if (!Array.isArray(options.envPairs)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.envPairs', - 'Array', options.envPairs); + throw new ERR_INVALID_ARG_TYPE('options.envPairs', + 'Array', + options.envPairs); } options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd); } if (typeof options.file !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.file', 'string', - options.file); + throw new ERR_INVALID_ARG_TYPE('options.file', 'string', options.file); } this.spawnfile = options.file; @@ -299,8 +310,7 @@ ChildProcess.prototype.spawn = function(options) { else if (options.args === undefined) this.spawnargs = []; else - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.args', 'Array', - options.args); + throw new ERR_INVALID_ARG_TYPE('options.args', 'Array', options.args); var err = this._handle.spawn(options); @@ -587,8 +597,7 @@ function setupChannel(target, channel) { options = undefined; } else if (options !== undefined && (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); } options = Object.assign({ swallowErrors: false }, options); @@ -596,7 +605,7 @@ function setupChannel(target, channel) { if (this.connected) { return this._send(message, handle, options, callback); } - const ex = new errors.Error('ERR_IPC_CHANNEL_CLOSED'); + const ex = new ERR_IPC_CHANNEL_CLOSED(); if (typeof callback === 'function') { process.nextTick(callback, ex); } else { @@ -609,7 +618,7 @@ function setupChannel(target, channel) { assert(this.connected || this.channel); if (message === undefined) - throw new errors.TypeError('ERR_MISSING_ARGS', 'message'); + throw new ERR_MISSING_ARGS('message'); // Support legacy function signature if (typeof options === 'boolean') { @@ -636,7 +645,7 @@ function setupChannel(target, channel) { } else if (handle instanceof UDP) { message.type = 'dgram.Native'; } else { - throw new errors.TypeError('ERR_INVALID_HANDLE_TYPE'); + throw new ERR_INVALID_HANDLE_TYPE(); } // Queue-up message and handle if we haven't received ACK yet. @@ -736,7 +745,7 @@ function setupChannel(target, channel) { target.disconnect = function() { if (!this.connected) { - this.emit('error', new errors.Error('ERR_IPC_DISCONNECTED')); + this.emit('error', new ERR_IPC_DISCONNECTED()); return; } @@ -818,11 +827,10 @@ function _validateStdio(stdio, sync) { case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break; case 'inherit': stdio = [0, 1, 2]; break; default: - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'stdio', stdio); + throw new ERR_INVALID_OPT_VALUE('stdio', stdio); } } else if (!Array.isArray(stdio)) { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'stdio', util.inspect(stdio)); + throw new ERR_INVALID_OPT_VALUE('stdio', util.inspect(stdio)); } // At least 3 stdio will be created @@ -864,9 +872,9 @@ function _validateStdio(stdio, sync) { // Cleanup previously created pipes cleanup(); if (!sync) - throw new errors.Error('ERR_IPC_ONE_PIPE'); + throw new ERR_IPC_ONE_PIPE(); else - throw new errors.Error('ERR_IPC_SYNC_FORK'); + throw new ERR_IPC_SYNC_FORK(); } ipc = new Pipe(PipeConstants.IPC); @@ -901,14 +909,12 @@ function _validateStdio(stdio, sync) { } else if (isUint8Array(stdio) || typeof stdio === 'string') { if (!sync) { cleanup(); - throw new errors.TypeError('ERR_INVALID_SYNC_FORK_INPUT', - util.inspect(stdio)); + throw new ERR_INVALID_SYNC_FORK_INPUT(util.inspect(stdio)); } } else { // Cleanup cleanup(); - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'stdio', - util.inspect(stdio)); + throw new ERR_INVALID_OPT_VALUE('stdio', util.inspect(stdio)); } return acc; diff --git a/lib/internal/crypto/certificate.js b/lib/internal/crypto/certificate.js index b6b6ef8f5f6dd0..5eaa5ce05645bf 100644 --- a/lib/internal/crypto/certificate.js +++ b/lib/internal/crypto/certificate.js @@ -6,7 +6,7 @@ const { certVerifySpkac } = process.binding('crypto'); -const errors = require('internal/errors'); +const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes; const { isArrayBufferView } = require('internal/util/types'); const { @@ -15,8 +15,10 @@ const { function verifySpkac(spkac) { if (!isArrayBufferView(spkac)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'spkac', - ['Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'spkac', + ['Buffer', 'TypedArray', 'DataView'] + ); } return certVerifySpkac(spkac); } @@ -24,8 +26,10 @@ function verifySpkac(spkac) { function exportPublicKey(spkac, encoding) { spkac = toBuf(spkac, encoding); if (!isArrayBufferView(spkac)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'spkac', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'spkac', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } return certExportPublicKey(spkac); } @@ -33,8 +37,10 @@ function exportPublicKey(spkac, encoding) { function exportChallenge(spkac, encoding) { spkac = toBuf(spkac, encoding); if (!isArrayBufferView(spkac)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'spkac', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'spkac', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } return certExportChallenge(spkac); } diff --git a/lib/internal/crypto/cipher.js b/lib/internal/crypto/cipher.js index 5426c7e6edeed7..0d468c3b1321ab 100644 --- a/lib/internal/crypto/cipher.js +++ b/lib/internal/crypto/cipher.js @@ -5,7 +5,10 @@ const { RSA_PKCS1_PADDING } = process.binding('constants').crypto; -const errors = require('internal/errors'); +const { + ERR_CRYPTO_INVALID_STATE, + ERR_INVALID_ARG_TYPE +} = require('internal/errors').codes; const { getDefaultEncoding, @@ -64,12 +67,14 @@ function Cipher(cipher, password, options) { return new Cipher(cipher, password, options); if (typeof cipher !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'cipher', 'string'); + throw new ERR_INVALID_ARG_TYPE('cipher', 'string'); password = toBuf(password); if (!isArrayBufferView(password)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'password', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'password', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } this._handle = new CipherBase(true); @@ -103,8 +108,10 @@ Cipher.prototype.update = function update(data, inputEncoding, outputEncoding) { outputEncoding = outputEncoding || encoding; if (typeof data !== 'string' && !isArrayBufferView(data)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'data', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'data', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } const ret = this._handle.update(data, inputEncoding); @@ -133,38 +140,38 @@ Cipher.prototype.final = function final(outputEncoding) { Cipher.prototype.setAutoPadding = function setAutoPadding(ap) { if (this._handle.setAutoPadding(ap) === false) - throw new errors.Error('ERR_CRYPTO_INVALID_STATE', 'setAutoPadding'); + throw new ERR_CRYPTO_INVALID_STATE('setAutoPadding'); return this; }; Cipher.prototype.getAuthTag = function getAuthTag() { const ret = this._handle.getAuthTag(); if (ret === undefined) - throw new errors.Error('ERR_CRYPTO_INVALID_STATE', 'getAuthTag'); + throw new ERR_CRYPTO_INVALID_STATE('getAuthTag'); return ret; }; Cipher.prototype.setAuthTag = function setAuthTag(tagbuf) { if (!isArrayBufferView(tagbuf)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'buffer', - ['Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE('buffer', + ['Buffer', 'TypedArray', 'DataView']); } // Do not do a normal falsy check because the method returns // undefined if it succeeds. Returns false specifically if it // errored if (this._handle.setAuthTag(tagbuf) === false) - throw new errors.Error('ERR_CRYPTO_INVALID_STATE', 'setAuthTag'); + throw new ERR_CRYPTO_INVALID_STATE('setAuthTag'); return this; }; Cipher.prototype.setAAD = function setAAD(aadbuf) { if (!isArrayBufferView(aadbuf)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'buffer', - ['Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE('buffer', + ['Buffer', 'TypedArray', 'DataView']); } if (this._handle.setAAD(aadbuf) === false) - throw new errors.Error('ERR_CRYPTO_INVALID_STATE', 'setAAD'); + throw new ERR_CRYPTO_INVALID_STATE('setAAD'); return this; }; @@ -173,18 +180,22 @@ function Cipheriv(cipher, key, iv, options) { return new Cipheriv(cipher, key, iv, options); if (typeof cipher !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'cipher', 'string'); + throw new ERR_INVALID_ARG_TYPE('cipher', 'string'); key = toBuf(key); if (!isArrayBufferView(key)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'key', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } iv = toBuf(iv); if (iv !== null && !isArrayBufferView(iv)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'iv', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'iv', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } this._handle = new CipherBase(true); @@ -211,12 +222,14 @@ function Decipher(cipher, password, options) { return new Decipher(cipher, password, options); if (typeof cipher !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'cipher', 'string'); + throw new ERR_INVALID_ARG_TYPE('cipher', 'string'); password = toBuf(password); if (!isArrayBufferView(password)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'password', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'password', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } this._handle = new CipherBase(false); @@ -244,18 +257,22 @@ function Decipheriv(cipher, key, iv, options) { return new Decipheriv(cipher, key, iv, options); if (typeof cipher !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'cipher', 'string'); + throw new ERR_INVALID_ARG_TYPE('cipher', 'string'); key = toBuf(key); if (!isArrayBufferView(key)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'key', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } iv = toBuf(iv); if (iv !== null && !isArrayBufferView(iv)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'iv', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'iv', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } this._handle = new CipherBase(false); diff --git a/lib/internal/crypto/diffiehellman.js b/lib/internal/crypto/diffiehellman.js index 687bae83fdecbb..f6d525c215ca63 100644 --- a/lib/internal/crypto/diffiehellman.js +++ b/lib/internal/crypto/diffiehellman.js @@ -1,7 +1,11 @@ 'use strict'; const { Buffer } = require('buffer'); -const errors = require('internal/errors'); +const { + ERR_CRYPTO_ECDH_INVALID_FORMAT, + ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY, + ERR_INVALID_ARG_TYPE +} = require('internal/errors').codes; const { isArrayBufferView } = require('internal/util/types'); const { getDefaultEncoding, @@ -27,9 +31,10 @@ function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) { if (typeof sizeOrKey !== 'number' && typeof sizeOrKey !== 'string' && !isArrayBufferView(sizeOrKey)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'sizeOrKey', - ['number', 'string', 'Buffer', 'TypedArray', - 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'sizeOrKey', + ['number', 'string', 'Buffer', 'TypedArray', 'DataView'] + ); } if (keyEncoding) { @@ -97,7 +102,7 @@ function dhComputeSecret(key, inEnc, outEnc) { outEnc = outEnc || encoding; var ret = this._handle.computeSecret(toBuf(key, inEnc)); if (typeof ret === 'string') - throw new errors.Error('ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY'); + throw new ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY(); if (outEnc && outEnc !== 'buffer') ret = ret.toString(outEnc); return ret; @@ -175,7 +180,7 @@ function ECDH(curve) { return new ECDH(curve); if (typeof curve !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'curve', 'string'); + throw new ERR_INVALID_ARG_TYPE('curve', 'string'); this._handle = new _ECDH(curve); } @@ -202,7 +207,7 @@ ECDH.prototype.getPublicKey = function getPublicKey(encoding, format) { else if (format === 'uncompressed') f = POINT_CONVERSION_UNCOMPRESSED; else - throw new errors.TypeError('ERR_CRYPTO_ECDH_INVALID_FORMAT', format); + throw new ERR_CRYPTO_ECDH_INVALID_FORMAT(format); } else { f = POINT_CONVERSION_UNCOMPRESSED; } diff --git a/lib/internal/crypto/hash.js b/lib/internal/crypto/hash.js index 952cc34d21b129..41e00b88b9c74e 100644 --- a/lib/internal/crypto/hash.js +++ b/lib/internal/crypto/hash.js @@ -12,7 +12,12 @@ const { const { Buffer } = require('buffer'); -const errors = require('internal/errors'); +const { + ERR_CRYPTO_HASH_DIGEST_NO_UTF16, + ERR_CRYPTO_HASH_FINALIZED, + ERR_CRYPTO_HASH_UPDATE_FAILED, + ERR_INVALID_ARG_TYPE +} = require('internal/errors').codes; const { inherits } = require('util'); const { normalizeEncoding } = require('internal/util'); const { isArrayBufferView } = require('internal/util/types'); @@ -24,7 +29,7 @@ function Hash(algorithm, options) { if (!(this instanceof Hash)) return new Hash(algorithm, options); if (typeof algorithm !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'algorithm', 'string'); + throw new ERR_INVALID_ARG_TYPE('algorithm', 'string'); this._handle = new _Hash(algorithm); this[kState] = { [kFinalized]: false @@ -47,15 +52,15 @@ Hash.prototype._flush = function _flush(callback) { Hash.prototype.update = function update(data, encoding) { const state = this[kState]; if (state[kFinalized]) - throw new errors.Error('ERR_CRYPTO_HASH_FINALIZED'); + throw new ERR_CRYPTO_HASH_FINALIZED(); if (typeof data !== 'string' && !isArrayBufferView(data)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'data', - ['string', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE('data', + ['string', 'TypedArray', 'DataView']); } if (!this._handle.update(data, encoding || getDefaultEncoding())) - throw new errors.Error('ERR_CRYPTO_HASH_UPDATE_FAILED'); + throw new ERR_CRYPTO_HASH_UPDATE_FAILED(); return this; }; @@ -63,10 +68,10 @@ Hash.prototype.update = function update(data, encoding) { Hash.prototype.digest = function digest(outputEncoding) { const state = this[kState]; if (state[kFinalized]) - throw new errors.Error('ERR_CRYPTO_HASH_FINALIZED'); + throw new ERR_CRYPTO_HASH_FINALIZED(); outputEncoding = outputEncoding || getDefaultEncoding(); if (normalizeEncoding(outputEncoding) === 'utf16le') - throw new errors.Error('ERR_CRYPTO_HASH_DIGEST_NO_UTF16'); + throw new ERR_CRYPTO_HASH_DIGEST_NO_UTF16(); // Explicit conversion for backward compatibility. const ret = this._handle.digest(`${outputEncoding}`); @@ -79,10 +84,9 @@ function Hmac(hmac, key, options) { if (!(this instanceof Hmac)) return new Hmac(hmac, key, options); if (typeof hmac !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'hmac', 'string'); + throw new ERR_INVALID_ARG_TYPE('hmac', 'string'); if (typeof key !== 'string' && !isArrayBufferView(key)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key', - ['string', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE('key', ['string', 'TypedArray', 'DataView']); } this._handle = new _Hmac(); this._handle.init(hmac, toBuf(key)); @@ -100,7 +104,7 @@ Hmac.prototype.digest = function digest(outputEncoding) { const state = this[kState]; outputEncoding = outputEncoding || getDefaultEncoding(); if (normalizeEncoding(outputEncoding) === 'utf16le') - throw new errors.Error('ERR_CRYPTO_HASH_DIGEST_NO_UTF16'); + throw new ERR_CRYPTO_HASH_DIGEST_NO_UTF16(); if (state[kFinalized]) { const buf = Buffer.from(''); diff --git a/lib/internal/crypto/pbkdf2.js b/lib/internal/crypto/pbkdf2.js index e967e0a7945fc6..fdffcffad681b7 100644 --- a/lib/internal/crypto/pbkdf2.js +++ b/lib/internal/crypto/pbkdf2.js @@ -1,6 +1,11 @@ 'use strict'; -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CALLBACK, + ERR_CRYPTO_INVALID_DIGEST, + ERR_OUT_OF_RANGE +} = require('internal/errors').codes; const { getDefaultEncoding, toBuf @@ -20,7 +25,7 @@ function pbkdf2(password, salt, iterations, keylen, digest, callback) { } if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); return _pbkdf2(password, salt, iterations, keylen, digest, callback); } @@ -32,38 +37,35 @@ function pbkdf2Sync(password, salt, iterations, keylen, digest) { function _pbkdf2(password, salt, iterations, keylen, digest, callback) { if (digest !== null && typeof digest !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'digest', - ['string', 'null']); + throw new ERR_INVALID_ARG_TYPE('digest', ['string', 'null']); password = toBuf(password); salt = toBuf(salt); if (!isArrayBufferView(password)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'password', - ['string', 'Buffer', 'TypedArray']); + throw new ERR_INVALID_ARG_TYPE('password', + ['string', 'Buffer', 'TypedArray']); } if (!isArrayBufferView(salt)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'salt', - ['string', 'Buffer', 'TypedArray']); + throw new ERR_INVALID_ARG_TYPE('salt', ['string', 'Buffer', 'TypedArray']); } if (typeof iterations !== 'number') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'iterations', 'number'); + throw new ERR_INVALID_ARG_TYPE('iterations', 'number'); if (iterations < 0) - throw new errors.RangeError('ERR_OUT_OF_RANGE', - 'iterations', - 'a non-negative number', - iterations); + throw new ERR_OUT_OF_RANGE('iterations', + 'a non-negative number', + iterations); if (typeof keylen !== 'number') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'keylen', 'number'); + throw new ERR_INVALID_ARG_TYPE('keylen', 'number'); if (keylen < 0 || !Number.isFinite(keylen) || keylen > INT_MAX) { - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'keylen'); + throw new ERR_OUT_OF_RANGE('keylen'); } const encoding = getDefaultEncoding(); @@ -71,7 +73,7 @@ function _pbkdf2(password, salt, iterations, keylen, digest, callback) { if (encoding === 'buffer') { const ret = PBKDF2(password, salt, iterations, keylen, digest, callback); if (ret === -1) - throw new errors.TypeError('ERR_CRYPTO_INVALID_DIGEST', digest); + throw new ERR_CRYPTO_INVALID_DIGEST(digest); return ret; } @@ -83,11 +85,11 @@ function _pbkdf2(password, salt, iterations, keylen, digest, callback) { callback(er, ret); } if (PBKDF2(password, salt, iterations, keylen, digest, next) === -1) - throw new errors.TypeError('ERR_CRYPTO_INVALID_DIGEST', digest); + throw new ERR_CRYPTO_INVALID_DIGEST(digest); } else { const ret = PBKDF2(password, salt, iterations, keylen, digest); if (ret === -1) - throw new errors.TypeError('ERR_CRYPTO_INVALID_DIGEST', digest); + throw new ERR_CRYPTO_INVALID_DIGEST(digest); return ret.toString(encoding); } } diff --git a/lib/internal/crypto/random.js b/lib/internal/crypto/random.js index 9ffaa4de76f652..77ad06ee7b568d 100644 --- a/lib/internal/crypto/random.js +++ b/lib/internal/crypto/random.js @@ -1,6 +1,10 @@ 'use strict'; -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CALLBACK, + ERR_OUT_OF_RANGE +} = require('internal/errors').codes; const { isArrayBufferView } = require('internal/util/types'); const { randomBytes: _randomBytes, @@ -12,43 +16,42 @@ const kMaxUint32 = Math.pow(2, 32) - 1; function assertOffset(offset, length) { if (typeof offset !== 'number' || Number.isNaN(offset)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'offset', 'number'); + throw new ERR_INVALID_ARG_TYPE('offset', 'number'); } if (offset > kMaxUint32 || offset < 0) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'offset', 'uint32'); + throw new ERR_INVALID_ARG_TYPE('offset', 'uint32'); } if (offset > kMaxLength || offset > length) { - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'offset'); + throw new ERR_OUT_OF_RANGE('offset'); } } function assertSize(size, offset = 0, length = Infinity) { if (typeof size !== 'number' || Number.isNaN(size)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'size', 'number'); + throw new ERR_INVALID_ARG_TYPE('size', 'number'); } if (size > kMaxUint32 || size < 0) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'size', 'uint32'); + throw new ERR_INVALID_ARG_TYPE('size', 'uint32'); } if (size + offset > length || size > kMaxLength) { - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'size'); + throw new ERR_OUT_OF_RANGE('size'); } } function randomBytes(size, cb) { assertSize(size); if (cb !== undefined && typeof cb !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); return _randomBytes(size, cb); } function randomFillSync(buf, offset = 0, size) { if (!isArrayBufferView(buf)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'buf', 'ArrayBufferView'); + throw new ERR_INVALID_ARG_TYPE('buf', 'ArrayBufferView'); } const elementSize = buf.BYTES_PER_ELEMENT || 1; @@ -69,8 +72,7 @@ function randomFillSync(buf, offset = 0, size) { function randomFill(buf, offset, size, cb) { if (!isArrayBufferView(buf)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'buf', 'ArrayBufferView'); + throw new ERR_INVALID_ARG_TYPE('buf', 'ArrayBufferView'); } const elementSize = buf.BYTES_PER_ELEMENT || 1; @@ -84,7 +86,7 @@ function randomFill(buf, offset, size, cb) { offset *= elementSize; size = buf.byteLength - offset; } else if (typeof cb !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } if (size === undefined) { size = buf.byteLength - offset; diff --git a/lib/internal/crypto/sig.js b/lib/internal/crypto/sig.js index 9f1938290f70cf..688ad43ddddf63 100644 --- a/lib/internal/crypto/sig.js +++ b/lib/internal/crypto/sig.js @@ -1,6 +1,10 @@ 'use strict'; -const errors = require('internal/errors'); +const { + ERR_CRYPTO_SIGN_KEY_REQUIRED, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_OPT_VALUE +} = require('internal/errors').codes; const { Sign: _Sign, Verify: _Verify @@ -21,7 +25,7 @@ function Sign(algorithm, options) { if (!(this instanceof Sign)) return new Sign(algorithm, options); if (typeof algorithm !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'algorithm', 'string'); + throw new ERR_INVALID_ARG_TYPE('algorithm', 'string'); this._handle = new _Sign(); this._handle.init(algorithm); @@ -39,8 +43,10 @@ Sign.prototype.update = function update(data, encoding) { encoding = encoding || getDefaultEncoding(); data = toBuf(data, encoding); if (!isArrayBufferView(data)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'data', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'data', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } this._handle.update(data); return this; @@ -48,7 +54,7 @@ Sign.prototype.update = function update(data, encoding) { Sign.prototype.sign = function sign(options, encoding) { if (!options) - throw new errors.Error('ERR_CRYPTO_SIGN_KEY_REQUIRED'); + throw new ERR_CRYPTO_SIGN_KEY_REQUIRED(); var key = options.key || options; var passphrase = options.passphrase || null; @@ -59,9 +65,7 @@ Sign.prototype.sign = function sign(options, encoding) { if (options.padding === options.padding >> 0) { rsaPadding = options.padding; } else { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'padding', - options.padding); + throw new ERR_INVALID_OPT_VALUE('padding', options.padding); } } @@ -70,16 +74,16 @@ Sign.prototype.sign = function sign(options, encoding) { if (options.saltLength === options.saltLength >> 0) { pssSaltLength = options.saltLength; } else { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'saltLength', - options.saltLength); + throw new ERR_INVALID_OPT_VALUE('saltLength', options.saltLength); } } key = toBuf(key); if (!isArrayBufferView(key)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'key', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } var ret = this._handle.sign(key, passphrase, rsaPadding, pssSaltLength); @@ -96,7 +100,7 @@ function Verify(algorithm, options) { if (!(this instanceof Verify)) return new Verify(algorithm, options); if (typeof algorithm !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'algorithm', 'string'); + throw new ERR_INVALID_ARG_TYPE('algorithm', 'string'); this._handle = new _Verify(); this._handle.init(algorithm); @@ -118,9 +122,7 @@ Verify.prototype.verify = function verify(options, signature, sigEncoding) { if (options.padding === options.padding >> 0) { rsaPadding = options.padding; } else { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'padding', - options.padding); + throw new ERR_INVALID_OPT_VALUE('padding', options.padding); } } @@ -129,22 +131,24 @@ Verify.prototype.verify = function verify(options, signature, sigEncoding) { if (options.saltLength === options.saltLength >> 0) { pssSaltLength = options.saltLength; } else { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'saltLength', - options.saltLength); + throw new ERR_INVALID_OPT_VALUE('saltLength', options.saltLength); } } key = toBuf(key); if (!isArrayBufferView(key)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'key', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } signature = toBuf(signature, sigEncoding); if (!isArrayBufferView(signature)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'signature', - ['string', 'Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE( + 'signature', + ['string', 'Buffer', 'TypedArray', 'DataView'] + ); } return this._handle.verify(key, signature, rsaPadding, pssSaltLength); diff --git a/lib/internal/crypto/util.js b/lib/internal/crypto/util.js index ac01a447bc4324..19c35ac4cdff58 100644 --- a/lib/internal/crypto/util.js +++ b/lib/internal/crypto/util.js @@ -12,7 +12,11 @@ const { ENGINE_METHOD_ALL } = process.binding('constants').crypto; -const errors = require('internal/errors'); +const { + ERR_CRYPTO_ENGINE_UNKNOWN, + ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH, + ERR_INVALID_ARG_TYPE +} = require('internal/errors').codes; const { Buffer } = require('buffer'); const { cachedResult, @@ -50,10 +54,10 @@ const getCurves = cachedResult(() => filterDuplicateStrings(_getCurves())); function setEngine(id, flags) { if (typeof id !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'id', 'string'); + throw new ERR_INVALID_ARG_TYPE('id', 'string'); if (flags && typeof flags !== 'number') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'flags', 'number'); + throw new ERR_INVALID_ARG_TYPE('flags', 'number'); flags = flags >>> 0; // Use provided engine for everything by default @@ -61,20 +65,18 @@ function setEngine(id, flags) { flags = ENGINE_METHOD_ALL; if (!_setEngine(id, flags)) - throw new errors.Error('ERR_CRYPTO_ENGINE_UNKNOWN', id); + throw new ERR_CRYPTO_ENGINE_UNKNOWN(id); } function timingSafeEqual(a, b) { if (!isArrayBufferView(a)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'a', - ['Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE('a', ['Buffer', 'TypedArray', 'DataView']); } if (!isArrayBufferView(b)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'b', - ['Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE('b', ['Buffer', 'TypedArray', 'DataView']); } if (a.length !== b.length) { - throw new errors.RangeError('ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH'); + throw new ERR_CRYPTO_TIMING_SAFE_EQUAL_LENGTH(); } return _timingSafeEqual(a, b); } diff --git a/lib/internal/encoding.js b/lib/internal/encoding.js index fc8ac555fc616c..1846fc552735a2 100644 --- a/lib/internal/encoding.js +++ b/lib/internal/encoding.js @@ -3,7 +3,13 @@ // An implementation of the WHATWG Encoding Standard // https://encoding.spec.whatwg.org -const errors = require('internal/errors'); +const { + ERR_ENCODING_INVALID_ENCODED_DATA, + ERR_ENCODING_NOT_SUPPORTED, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_THIS, + ERR_NO_ICU +} = require('internal/errors').codes; const kHandle = Symbol('handle'); const kFlags = Symbol('flags'); const kEncoding = Symbol('encoding'); @@ -35,17 +41,17 @@ function lazyBuffer() { function validateEncoder(obj) { if (obj == null || obj[kEncoder] !== true) - throw new errors.TypeError('ERR_INVALID_THIS', 'TextEncoder'); + throw new ERR_INVALID_THIS('TextEncoder'); } function validateDecoder(obj) { if (obj == null || obj[kDecoder] !== true) - throw new errors.TypeError('ERR_INVALID_THIS', 'TextDecoder'); + throw new ERR_INVALID_THIS('TextDecoder'); } function validateArgument(prop, expected, propName, expectedName) { if (typeof prop !== expected) - throw new errors.Error('ERR_INVALID_ARG_TYPE', propName, expectedName); + throw new ERR_INVALID_ARG_TYPE(propName, expectedName); } const CONVERTER_FLAGS_FLUSH = 0x1; @@ -360,7 +366,7 @@ function makeTextDecoderICU() { const enc = getEncodingFromLabel(encoding); if (enc === undefined) - throw new errors.RangeError('ERR_ENCODING_NOT_SUPPORTED', encoding); + throw new ERR_ENCODING_NOT_SUPPORTED(encoding); var flags = 0; if (options !== null) { @@ -370,7 +376,7 @@ function makeTextDecoderICU() { const handle = getConverter(enc, flags); if (handle === undefined) - throw new errors.Error('ERR_ENCODING_NOT_SUPPORTED', encoding); + throw new ERR_ENCODING_NOT_SUPPORTED(encoding); this[kDecoder] = true; this[kHandle] = handle; @@ -384,8 +390,8 @@ function makeTextDecoderICU() { if (isArrayBuffer(input)) { input = lazyBuffer().from(input); } else if (!isArrayBufferView(input)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'input', - ['ArrayBuffer', 'ArrayBufferView']); + throw new ERR_INVALID_ARG_TYPE('input', + ['ArrayBuffer', 'ArrayBufferView']); } validateArgument(options, 'object', 'options', 'Object'); @@ -395,8 +401,7 @@ function makeTextDecoderICU() { const ret = _decode(this[kHandle], input, flags); if (typeof ret === 'number') { - const err = new errors.TypeError('ERR_ENCODING_INVALID_ENCODED_DATA', - this.encoding); + const err = new ERR_ENCODING_INVALID_ENCODED_DATA(this.encoding); err.errno = ret; throw err; } @@ -428,12 +433,12 @@ function makeTextDecoderJS() { const enc = getEncodingFromLabel(encoding); if (enc === undefined || !hasConverter(enc)) - throw new errors.RangeError('ERR_ENCODING_NOT_SUPPORTED', encoding); + throw new ERR_ENCODING_NOT_SUPPORTED(encoding); var flags = 0; if (options !== null) { if (options.fatal) { - throw new errors.TypeError('ERR_NO_ICU', '"fatal" option'); + throw new ERR_NO_ICU('"fatal" option'); } flags |= options.ignoreBOM ? CONVERTER_FLAGS_IGNORE_BOM : 0; } @@ -454,8 +459,8 @@ function makeTextDecoderJS() { input = lazyBuffer().from(input.buffer, input.byteOffset, input.byteLength); } else { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'input', - ['ArrayBuffer', 'ArrayBufferView']); + throw new ERR_INVALID_ARG_TYPE('input', + ['ArrayBuffer', 'ArrayBufferView']); } validateArgument(options, 'object', 'options', 'Object'); diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 0fdf795433a4dc..d5a5c4fc599619 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -320,7 +320,7 @@ function createErrDiff(actual, expected, operator) { class AssertionError extends Error { constructor(options) { if (typeof options !== 'object' || options === null) { - throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object'); + throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object'); } var { actual, @@ -600,7 +600,7 @@ module.exports = exports = { // Note: Node.js specific errors must begin with the prefix ERR_ E('ERR_ARG_NOT_ITERABLE', '%s must be iterable', TypeError); -E('ERR_ASSERTION', '%s', AssertionError); +E('ERR_ASSERTION', '%s', Error); E('ERR_ASYNC_CALLBACK', '%s must be a function', TypeError); E('ERR_ASYNC_TYPE', 'Invalid name for async "type": %s', TypeError); E('ERR_BUFFER_OUT_OF_BOUNDS', bufferOutOfBounds, RangeError); @@ -622,7 +622,7 @@ E('ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED', 'Custom engines not supported by this OpenSSL', Error); E('ERR_CRYPTO_ECDH_INVALID_FORMAT', 'Invalid ECDH format: %s', TypeError); E('ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY', - 'Public key is not valid for specified curve', TypeError); + 'Public key is not valid for specified curve', Error); E('ERR_CRYPTO_ENGINE_UNKNOWN', 'Engine "%s" was not found', Error); E('ERR_CRYPTO_FIPS_FORCED', 'Cannot set FIPS mode, it was forced with --force-fips at startup.', Error); @@ -653,7 +653,7 @@ E('ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE', E('ERR_ENCODING_INVALID_ENCODED_DATA', 'The encoded data was not valid for encoding %s', TypeError); E('ERR_ENCODING_NOT_SUPPORTED', 'The "%s" encoding is not supported', - RangeError); // One entry is currently falsy implemented as "Error" + RangeError); E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value', Error); E('ERR_FS_INVALID_SYMLINK_TYPE', 'Symlink type must be one of "dir", "file", or "junction". Received "%s"', @@ -846,7 +846,7 @@ E('ERR_SOCKET_DGRAM_NOT_RUNNING', 'Not running', Error); E('ERR_STDERR_CLOSE', 'process.stderr cannot be closed', Error); E('ERR_STDOUT_CLOSE', 'process.stdout cannot be closed', Error); E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error); -E('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed'); +E('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error); E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error); E('ERR_STREAM_READ_NOT_IMPLEMENTED', '_read() is not implemented', Error); diff --git a/lib/internal/fs.js b/lib/internal/fs.js index 04844248b0b8e0..36155d4d67f1f5 100644 --- a/lib/internal/fs.js +++ b/lib/internal/fs.js @@ -2,7 +2,14 @@ const { Buffer, kMaxLength } = require('buffer'); const { Writable } = require('stream'); -const errors = require('internal/errors'); +const { + ERR_FS_INVALID_SYMLINK_TYPE, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARG_VALUE, + ERR_INVALID_OPT_VALUE, + ERR_INVALID_OPT_VALUE_ENCODING, + ERR_OUT_OF_RANGE +} = require('internal/errors').codes; const { isUint8Array } = require('internal/util/types'); const fs = require('fs'); const pathModule = require('path'); @@ -34,7 +41,7 @@ const isWindows = process.platform === 'win32'; function assertEncoding(encoding) { if (encoding && !Buffer.isEncoding(encoding)) { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE_ENCODING', encoding); + throw new ERR_INVALID_OPT_VALUE_ENCODING(encoding); } } @@ -56,10 +63,7 @@ function getOptions(options, defaultOptions) { defaultOptions.encoding = options; options = defaultOptions; } else if (typeof options !== 'object') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'options', - ['string', 'Object'], - options); + throw new ERR_INVALID_ARG_TYPE('options', ['string', 'Object'], options); } if (options.encoding !== 'buffer') @@ -97,9 +101,11 @@ function nullCheck(path, propName, throwError = true) { return; } - const err = new errors.Error( - 'ERR_INVALID_ARG_VALUE', propName, path, - 'must be a string or Uint8Array without null bytes'); + const err = new ERR_INVALID_ARG_VALUE( + propName, + path, + 'must be a string or Uint8Array without null bytes' + ); if (throwError) { Error.captureStackTrace(err, nullCheck); @@ -233,7 +239,7 @@ function stringToFlags(flags) { case 'sa+': return O_APPEND | O_CREAT | O_RDWR | O_SYNC; } - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'flags', flags); + throw new ERR_INVALID_OPT_VALUE('flags', flags); } function stringToSymlinkType(type) { @@ -249,7 +255,7 @@ function stringToSymlinkType(type) { case 'file': break; default: - const err = new errors.Error('ERR_FS_INVALID_SYMLINK_TYPE', type); + const err = new ERR_FS_INVALID_SYMLINK_TYPE(type); Error.captureStackTrace(err, stringToSymlinkType); throw err; } @@ -312,16 +318,12 @@ function toUnixTimestamp(time, name = 'time') { // convert to 123.456 UNIX timestamp return time.getTime() / 1000; } - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - name, - ['Date', 'Time in seconds'], - time); + throw new ERR_INVALID_ARG_TYPE(name, ['Date', 'Time in seconds'], time); } function validateBuffer(buffer) { if (!isUint8Array(buffer)) { - const err = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'buffer', - ['Buffer', 'Uint8Array']); + const err = new ERR_INVALID_ARG_TYPE('buffer', ['Buffer', 'Uint8Array']); Error.captureStackTrace(err, validateBuffer); throw err; } @@ -331,7 +333,7 @@ function validateLen(len) { let err; if (!isInt32(len)) - err = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'len', 'integer'); + err = new ERR_INVALID_ARG_TYPE('len', 'integer'); if (err !== undefined) { Error.captureStackTrace(err, validateLen); @@ -343,9 +345,9 @@ function validateOffsetLengthRead(offset, length, bufferLength) { let err; if (offset < 0 || offset >= bufferLength) { - err = new errors.RangeError('ERR_OUT_OF_RANGE', 'offset'); + err = new ERR_OUT_OF_RANGE('offset'); } else if (length < 0 || offset + length > bufferLength) { - err = new errors.RangeError('ERR_OUT_OF_RANGE', 'length'); + err = new ERR_OUT_OF_RANGE('length'); } if (err !== undefined) { @@ -358,9 +360,9 @@ function validateOffsetLengthWrite(offset, length, byteLength) { let err; if (offset > byteLength) { - err = new errors.RangeError('ERR_OUT_OF_RANGE', 'offset'); + err = new ERR_OUT_OF_RANGE('offset'); } else if (offset + length > byteLength || offset + length > kMaxLength) { - err = new errors.RangeError('ERR_OUT_OF_RANGE', 'length'); + err = new ERR_OUT_OF_RANGE('length'); } if (err !== undefined) { @@ -377,8 +379,7 @@ function validatePath(path, propName) { } if (typeof path !== 'string' && !isUint8Array(path)) { - err = new errors.TypeError('ERR_INVALID_ARG_TYPE', propName, - ['string', 'Buffer', 'URL']); + err = new ERR_INVALID_ARG_TYPE(propName, ['string', 'Buffer', 'URL']); } else { err = nullCheck(path, propName, false); } @@ -393,7 +394,7 @@ function validateUint32(value, propName) { let err; if (!isUint32(value)) - err = new errors.TypeError('ERR_INVALID_ARG_TYPE', propName, 'integer'); + err = new ERR_INVALID_ARG_TYPE(propName, 'integer'); if (err !== undefined) { Error.captureStackTrace(err, validateUint32); diff --git a/lib/internal/http2/compat.js b/lib/internal/http2/compat.js index 9670843176b77e..6ec6cb33cb7b0f 100644 --- a/lib/internal/http2/compat.js +++ b/lib/internal/http2/compat.js @@ -4,7 +4,18 @@ const Stream = require('stream'); const Readable = Stream.Readable; const binding = process.binding('http2'); const constants = binding.constants; -const errors = require('internal/errors'); +const { + ERR_HTTP2_HEADERS_SENT, + ERR_HTTP2_INFO_STATUS_NOT_ALLOWED, + ERR_HTTP2_INVALID_HEADER_VALUE, + ERR_HTTP2_INVALID_STREAM, + ERR_HTTP2_NO_SOCKET_MANIPULATION, + ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED, + ERR_HTTP2_STATUS_INVALID, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CALLBACK, + ERR_INVALID_HTTP_TOKEN +} = require('internal/errors').codes; const { kSocket } = require('internal/http2/util'); const kFinish = Symbol('finish'); @@ -42,11 +53,11 @@ let statusMessageWarned = false; function assertValidHeader(name, value) { let err; if (name === '' || typeof name !== 'string') { - err = new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Header name', name); + err = new ERR_INVALID_HTTP_TOKEN('Header name', name); } else if (isPseudoHeader(name)) { - err = new errors.Error('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED'); + err = new ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED(); } else if (value === undefined || value === null) { - err = new errors.TypeError('ERR_HTTP2_INVALID_HEADER_VALUE', value, name); + err = new ERR_HTTP2_INVALID_HEADER_VALUE(value, name); } if (err !== undefined) { Error.captureStackTrace(err, assertValidHeader); @@ -163,7 +174,7 @@ const proxySocketHandler = { case 'read': case 'pause': case 'resume': - throw new errors.Error('ERR_HTTP2_NO_SOCKET_MANIPULATION'); + throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); default: const ref = stream.session !== undefined ? stream.session[kSocket] : stream; @@ -199,7 +210,7 @@ const proxySocketHandler = { case 'read': case 'pause': case 'resume': - throw new errors.Error('ERR_HTTP2_NO_SOCKET_MANIPULATION'); + throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); default: const ref = stream.session !== undefined ? stream.session[kSocket] : stream; @@ -292,7 +303,7 @@ class Http2ServerRequest extends Readable { state.didRead = true; process.nextTick(resumeStream, this[kStream]); } else { - this.emit('error', new errors.Error('ERR_HTTP2_INVALID_STREAM')); + this.emit('error', new ERR_HTTP2_INVALID_STREAM()); } } @@ -302,7 +313,7 @@ class Http2ServerRequest extends Readable { set method(method) { if (typeof method !== 'string' || method.trim() === '') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'method', 'string'); + throw new ERR_INVALID_ARG_TYPE('method', 'string'); this[kHeaders][HTTP2_HEADER_METHOD] = method; } @@ -419,15 +430,15 @@ class Http2ServerResponse extends Stream { set statusCode(code) { code |= 0; if (code >= 100 && code < 200) - throw new errors.RangeError('ERR_HTTP2_INFO_STATUS_NOT_ALLOWED'); + throw new ERR_HTTP2_INFO_STATUS_NOT_ALLOWED(); if (code < 100 || code > 599) - throw new errors.RangeError('ERR_HTTP2_STATUS_INVALID', code); + throw new ERR_HTTP2_STATUS_INVALID(code); this[kState].statusCode = code; } setTrailer(name, value) { if (typeof name !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + throw new ERR_INVALID_ARG_TYPE('name', 'string'); name = name.trim().toLowerCase(); assertValidHeader(name, value); @@ -445,7 +456,7 @@ class Http2ServerResponse extends Stream { getHeader(name) { if (typeof name !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + throw new ERR_INVALID_ARG_TYPE('name', 'string'); name = name.trim().toLowerCase(); return this[kHeaders][name]; @@ -461,7 +472,7 @@ class Http2ServerResponse extends Stream { hasHeader(name) { if (typeof name !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + throw new ERR_INVALID_ARG_TYPE('name', 'string'); name = name.trim().toLowerCase(); return Object.prototype.hasOwnProperty.call(this[kHeaders], name); @@ -469,10 +480,10 @@ class Http2ServerResponse extends Stream { removeHeader(name) { if (typeof name !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + throw new ERR_INVALID_ARG_TYPE('name', 'string'); if (this[kStream].headersSent) - throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); + throw new ERR_HTTP2_HEADERS_SENT(); name = name.trim().toLowerCase(); delete this[kHeaders][name]; @@ -480,10 +491,10 @@ class Http2ServerResponse extends Stream { setHeader(name, value) { if (typeof name !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'name', 'string'); + throw new ERR_INVALID_ARG_TYPE('name', 'string'); if (this[kStream].headersSent) - throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); + throw new ERR_HTTP2_HEADERS_SENT(); this[kSetHeader](name, value); } @@ -514,9 +525,9 @@ class Http2ServerResponse extends Stream { const state = this[kState]; if (state.closed) - throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); + throw new ERR_HTTP2_INVALID_STREAM(); if (this[kStream].headersSent) - throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); + throw new ERR_HTTP2_HEADERS_SENT(); if (typeof statusMessage === 'string') statusMessageWarn(); @@ -544,7 +555,7 @@ class Http2ServerResponse extends Stream { } if (this[kState].closed) { - const err = new errors.Error('ERR_HTTP2_INVALID_STREAM'); + const err = new ERR_HTTP2_INVALID_STREAM(); if (typeof cb === 'function') process.nextTick(cb, err); else @@ -614,9 +625,9 @@ class Http2ServerResponse extends Stream { createPushResponse(headers, callback) { if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); if (this[kState].closed) { - process.nextTick(callback, new errors.Error('ERR_HTTP2_INVALID_STREAM')); + process.nextTick(callback, new ERR_HTTP2_INVALID_STREAM()); return; } this[kStream].pushStream(headers, {}, (err, stream, headers, options) => { diff --git a/lib/internal/http2/core.js b/lib/internal/http2/core.js index f60c6388af6cec..c764cd0297feda 100644 --- a/lib/internal/http2/core.js +++ b/lib/internal/http2/core.js @@ -14,7 +14,47 @@ const net = require('net'); const tls = require('tls'); const util = require('util'); const fs = require('fs'); -const errors = require('internal/errors'); +const { + errnoException, + codes: { + ERR_HTTP2_ALTSVC_INVALID_ORIGIN, + ERR_HTTP2_ALTSVC_LENGTH, + ERR_HTTP2_CONNECT_AUTHORITY, + ERR_HTTP2_CONNECT_PATH, + ERR_HTTP2_CONNECT_SCHEME, + ERR_HTTP2_GOAWAY_SESSION, + ERR_HTTP2_HEADERS_AFTER_RESPOND, + ERR_HTTP2_HEADERS_SENT, + ERR_HTTP2_INVALID_INFO_STATUS, + ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH, + ERR_HTTP2_INVALID_SESSION, + ERR_HTTP2_INVALID_SETTING_VALUE, + ERR_HTTP2_INVALID_STREAM, + ERR_HTTP2_MAX_PENDING_SETTINGS_ACK, + ERR_HTTP2_NO_SOCKET_MANIPULATION, + ERR_HTTP2_OUT_OF_STREAMS, + ERR_HTTP2_PAYLOAD_FORBIDDEN, + ERR_HTTP2_PING_CANCEL, + ERR_HTTP2_PING_LENGTH, + ERR_HTTP2_PUSH_DISABLED, + ERR_HTTP2_SEND_FILE, + ERR_HTTP2_SESSION_ERROR, + ERR_HTTP2_SETTINGS_CANCEL, + ERR_HTTP2_SOCKET_BOUND, + ERR_HTTP2_STATUS_101, + ERR_HTTP2_STATUS_INVALID, + ERR_HTTP2_STREAM_CANCEL, + ERR_HTTP2_STREAM_ERROR, + ERR_HTTP2_STREAM_SELF_DEPENDENCY, + ERR_HTTP2_UNSUPPORTED_PROTOCOL, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CALLBACK, + ERR_INVALID_CHAR, + ERR_INVALID_OPT_VALUE, + ERR_OUT_OF_RANGE, + ERR_SOCKET_CLOSED + } +} = require('internal/errors'); const { StreamWrap } = require('_stream_wrap'); const { Duplex } = require('stream'); const { URL } = require('url'); @@ -437,7 +477,7 @@ function onGoawayData(code, lastStreamID, buf) { // goaway using NGHTTP2_NO_ERROR because there was no error // condition on this side of the session that caused the // shutdown. - session.destroy(new errors.Error('ERR_HTTP2_SESSION_ERROR', code), + session.destroy(new ERR_HTTP2_SESSION_ERROR(code), { errorCode: NGHTTP2_NO_ERROR }); } } @@ -468,7 +508,7 @@ function requestOnConnect(headers, options) { // If the session was closed while waiting for the connect, destroy // the stream and do not continue with the request. if (session.closed) { - const err = new errors.Error('ERR_HTTP2_GOAWAY_SESSION'); + const err = new ERR_HTTP2_GOAWAY_SESSION(); this.destroy(err); return; } @@ -506,11 +546,11 @@ function requestOnConnect(headers, options) { let err; switch (ret) { case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE: - err = new errors.Error('ERR_HTTP2_OUT_OF_STREAMS'); + err = new ERR_HTTP2_OUT_OF_STREAMS(); this.destroy(err); break; case NGHTTP2_ERR_INVALID_ARGUMENT: - err = new errors.Error('ERR_HTTP2_STREAM_SELF_DEPENDENCY'); + err = new ERR_HTTP2_STREAM_SELF_DEPENDENCY(); this.destroy(err); break; default: @@ -533,33 +573,25 @@ function validatePriorityOptions(options) { if (options.weight === undefined) { options.weight = NGHTTP2_DEFAULT_WEIGHT; } else if (typeof options.weight !== 'number') { - err = new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'weight', - options.weight); + err = new ERR_INVALID_OPT_VALUE('weight', options.weight); } if (options.parent === undefined) { options.parent = 0; } else if (typeof options.parent !== 'number' || options.parent < 0) { - err = new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'parent', - options.parent); + err = new ERR_INVALID_OPT_VALUE('parent', options.parent); } if (options.exclusive === undefined) { options.exclusive = false; } else if (typeof options.exclusive !== 'boolean') { - err = new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'exclusive', - options.exclusive); + err = new ERR_INVALID_OPT_VALUE('exclusive', options.exclusive); } if (options.silent === undefined) { options.silent = false; } else if (typeof options.silent !== 'boolean') { - err = new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'silent', - options.silent); + err = new ERR_INVALID_OPT_VALUE('silent', options.silent); } if (err) { @@ -587,7 +619,7 @@ function settingsCallback(cb, ack, duration) { } else { debug(`Http2Session ${sessionName(this[kType])}: settings canceled`); if (typeof cb === 'function') - cb(new errors.Error('ERR_HTTP2_SETTINGS_CANCEL')); + cb(new ERR_HTTP2_SETTINGS_CANCEL()); } } @@ -599,7 +631,7 @@ function submitSettings(settings, callback) { this[kUpdateTimer](); updateSettingsBuffer(settings); if (!this[kHandle].settings(settingsCallback.bind(this, callback))) { - this.destroy(new errors.Error('ERR_HTTP2_MAX_PENDING_SETTINGS_ACK')); + this.destroy(new ERR_HTTP2_MAX_PENDING_SETTINGS_ACK()); } } @@ -646,7 +678,7 @@ const proxySocketHandler = { case 'read': case 'resume': case 'write': - throw new errors.Error('ERR_HTTP2_NO_SOCKET_MANIPULATION'); + throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); default: const socket = session[kSocket]; const value = socket[prop]; @@ -668,7 +700,7 @@ const proxySocketHandler = { case 'read': case 'resume': case 'write': - throw new errors.Error('ERR_HTTP2_NO_SOCKET_MANIPULATION'); + throw new ERR_HTTP2_NO_SOCKET_MANIPULATION(); default: session[kSocket][prop] = value; return true; @@ -684,7 +716,7 @@ const proxySocketHandler = { // data received on the PING acknowlegement. function pingCallback(cb) { return function pingCallback(ack, duration, payload) { - const err = ack ? null : new errors.Error('ERR_HTTP2_PING_CANCEL'); + const err = ack ? null : new ERR_HTTP2_PING_CANCEL(); cb(err, duration, payload); }; } @@ -716,8 +748,8 @@ function validateSettings(settings) { 0, kMaxInt); if (settings.enablePush !== undefined && typeof settings.enablePush !== 'boolean') { - const err = new errors.TypeError('ERR_HTTP2_INVALID_SETTING_VALUE', - 'enablePush', settings.enablePush); + const err = new ERR_HTTP2_INVALID_SETTING_VALUE('enablePush', + settings.enablePush); err.actual = settings.enablePush; Error.captureStackTrace(err, 'validateSettings'); throw err; @@ -838,7 +870,7 @@ class Http2Session extends EventEmitter { // then it has already been bound to an Http2Session instance // and cannot be attached again. if (socket[kSession] !== undefined) - throw new errors.Error('ERR_HTTP2_SOCKET_BOUND'); + throw new ERR_HTTP2_SOCKET_BOUND(); socket[kSession] = this; @@ -945,13 +977,12 @@ class Http2Session extends EventEmitter { // value also needs to be larger than the current next stream ID. setNextStreamID(id) { if (this.destroyed) - throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); + throw new ERR_HTTP2_INVALID_SESSION(); if (typeof id !== 'number') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'id', 'number'); + throw new ERR_INVALID_ARG_TYPE('id', 'number'); if (id <= 0 || id > kMaxStreams) - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'id', - `> 0 and <= ${kMaxStreams}`, id); + throw new ERR_OUT_OF_RANGE('id', `> 0 and <= ${kMaxStreams}`, id); this[kHandle].setNextStreamID(id); } @@ -960,22 +991,21 @@ class Http2Session extends EventEmitter { // cancelled error and a duration of 0.0. ping(payload, callback) { if (this.destroyed) - throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); + throw new ERR_HTTP2_INVALID_SESSION(); if (typeof payload === 'function') { callback = payload; payload = undefined; } if (payload && !isArrayBufferView(payload)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'payload', - ['Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE('payload', + ['Buffer', 'TypedArray', 'DataView']); } if (payload && payload.length !== 8) { - throw new errors.RangeError('ERR_HTTP2_PING_LENGTH'); + throw new ERR_HTTP2_PING_LENGTH(); } if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); const cb = pingCallback(callback); if (this.connecting || this.closed) { @@ -1060,12 +1090,12 @@ class Http2Session extends EventEmitter { // Submits a SETTINGS frame to be sent to the remote peer. settings(settings, callback) { if (this.destroyed) - throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); + throw new ERR_HTTP2_INVALID_SESSION(); assertIsObject(settings, 'settings'); settings = validateSettings(settings); if (callback && typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); debug(`Http2Session ${sessionName(this[kType])}: sending settings`); this[kState].pendingAck++; @@ -1084,19 +1114,17 @@ class Http2Session extends EventEmitter { // be rejected automatically. goaway(code = NGHTTP2_NO_ERROR, lastStreamID = 0, opaqueData) { if (this.destroyed) - throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); + throw new ERR_HTTP2_INVALID_SESSION(); if (opaqueData !== undefined && !isArrayBufferView(opaqueData)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'opaqueData', - ['Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE('opaqueData', + ['Buffer', 'TypedArray', 'DataView']); } if (typeof code !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'code', 'number'); + throw new ERR_INVALID_ARG_TYPE('code', 'number'); } if (typeof lastStreamID !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'lastStreamID', 'number'); + throw new ERR_INVALID_ARG_TYPE('lastStreamID', 'number'); } const goawayFn = submitGoaway.bind(this, code, lastStreamID, opaqueData); @@ -1118,7 +1146,7 @@ class Http2Session extends EventEmitter { code = error; error = code !== NGHTTP2_NO_ERROR ? - new errors.Error('ERR_HTTP2_SESSION_ERROR', code) : undefined; + new ERR_HTTP2_SESSION_ERROR(code) : undefined; } if (code === undefined && error != null) code = NGHTTP2_INTERNAL_ERROR; @@ -1131,7 +1159,7 @@ class Http2Session extends EventEmitter { this.removeAllListeners('timeout'); // Destroy any pending and open streams - const cancel = new errors.Error('ERR_HTTP2_STREAM_CANCEL'); + const cancel = new ERR_HTTP2_STREAM_CANCEL(); if (error) { cancel.cause = error; if (typeof error.message === 'string') @@ -1265,7 +1293,7 @@ class ServerHttp2Session extends Http2Session { // API is provided for that. altsvc(alt, originOrStream) { if (this.destroyed) - throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); + throw new ERR_HTTP2_INVALID_SESSION(); let stream = 0; let origin; @@ -1273,10 +1301,10 @@ class ServerHttp2Session extends Http2Session { if (typeof originOrStream === 'string') { origin = (new URL(originOrStream)).origin; if (origin === 'null') - throw new errors.TypeError('ERR_HTTP2_ALTSVC_INVALID_ORIGIN'); + throw new ERR_HTTP2_ALTSVC_INVALID_ORIGIN(); } else if (typeof originOrStream === 'number') { if (originOrStream >>> 0 !== originOrStream || originOrStream === 0) - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'originOrStream'); + throw new ERR_OUT_OF_RANGE('originOrStream'); stream = originOrStream; } else if (originOrStream !== undefined) { // Allow origin to be passed a URL or object with origin property @@ -1288,21 +1316,21 @@ class ServerHttp2Session extends Http2Session { // ensure they are doing the right thing or the payload data will // be invalid. if (typeof origin !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'originOrStream', - ['string', 'number', 'URL', 'object']); + throw new ERR_INVALID_ARG_TYPE('originOrStream', + ['string', 'number', 'URL', 'object']); } else if (origin === 'null' || origin.length === 0) { - throw new errors.TypeError('ERR_HTTP2_ALTSVC_INVALID_ORIGIN'); + throw new ERR_HTTP2_ALTSVC_INVALID_ORIGIN(); } } if (typeof alt !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'alt', 'string'); + throw new ERR_INVALID_ARG_TYPE('alt', 'string'); if (!kQuotedString.test(alt)) - throw new errors.TypeError('ERR_INVALID_CHAR', 'alt'); + throw new ERR_INVALID_CHAR('alt'); // Max length permitted for ALTSVC if ((alt.length + (origin !== undefined ? origin.length : 0)) > 16382) - throw new errors.TypeError('ERR_HTTP2_ALTSVC_LENGTH'); + throw new ERR_HTTP2_ALTSVC_LENGTH(); this[kHandle].altsvc(stream, origin || '', alt); } @@ -1323,10 +1351,10 @@ class ClientHttp2Session extends Http2Session { debug(`Http2Session ${sessionName(this[kType])}: initiating request`); if (this.destroyed) - throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); + throw new ERR_HTTP2_INVALID_SESSION(); if (this.closed) - throw new errors.Error('ERR_HTTP2_GOAWAY_SESSION'); + throw new ERR_HTTP2_GOAWAY_SESSION(); this[kUpdateTimer](); @@ -1350,11 +1378,11 @@ class ClientHttp2Session extends Http2Session { headers[HTTP2_HEADER_PATH] = '/'; } else { if (headers[HTTP2_HEADER_AUTHORITY] === undefined) - throw new errors.Error('ERR_HTTP2_CONNECT_AUTHORITY'); + throw new ERR_HTTP2_CONNECT_AUTHORITY(); if (headers[HTTP2_HEADER_SCHEME] !== undefined) - throw new errors.Error('ERR_HTTP2_CONNECT_SCHEME'); + throw new ERR_HTTP2_CONNECT_SCHEME(); if (headers[HTTP2_HEADER_PATH] !== undefined) - throw new errors.Error('ERR_HTTP2_CONNECT_PATH'); + throw new ERR_HTTP2_CONNECT_PATH(); } validatePriorityOptions(options); @@ -1365,16 +1393,12 @@ class ClientHttp2Session extends Http2Session { // preference. options.endStream = isPayloadMeaningless(headers[HTTP2_HEADER_METHOD]); } else if (typeof options.endStream !== 'boolean') { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'endStream', - options.endStream); + throw new ERR_INVALID_OPT_VALUE('endStream', options.endStream); } if (options.getTrailers !== undefined && typeof options.getTrailers !== 'function') { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'getTrailers', - options.getTrailers); + throw new ERR_INVALID_OPT_VALUE('getTrailers', options.getTrailers); } const headersList = mapToHeaders(headers); @@ -1653,7 +1677,7 @@ class Http2Stream extends Duplex { req.async = false; const err = createWriteReq(req, handle, data, encoding); if (err) - throw errors.errnoException(err, 'write', req.error); + throw errnoException(err, 'write', req.error); trackWriteState(this, req.bytes); } @@ -1696,7 +1720,7 @@ class Http2Stream extends Duplex { } const err = handle.writev(req, chunks); if (err) - throw errors.errnoException(err, 'write', req.error); + throw errnoException(err, 'write', req.error); trackWriteState(this, req.bytes); } @@ -1731,7 +1755,7 @@ class Http2Stream extends Duplex { priority(options) { if (this.destroyed) - throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); + throw new ERR_HTTP2_INVALID_STREAM(); assertIsObject(options, 'options'); options = Object.assign({}, options); @@ -1767,11 +1791,11 @@ class Http2Stream extends Duplex { // but no DATA and HEADERS frames may be sent. close(code = NGHTTP2_NO_ERROR, callback) { if (typeof code !== 'number') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'code', 'number'); + throw new ERR_INVALID_ARG_TYPE('code', 'number'); if (code < 0 || code > kMaxInt) - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'code'); + throw new ERR_OUT_OF_RANGE('code'); if (callback !== undefined && typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); // Clear timeout and remove timeout listeners this.setTimeout(0); @@ -1850,8 +1874,7 @@ class Http2Stream extends Duplex { // abort and is already covered by aborted event, also allows more // seamless compatibility with http1 if (err == null && code !== NGHTTP2_NO_ERROR && code !== NGHTTP2_CANCEL) - err = new errors.Error('ERR_HTTP2_STREAM_ERROR', - nameForErrorCode[code] || code); + err = new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code); this[kSession] = undefined; this[kHandle] = undefined; @@ -1900,8 +1923,7 @@ function processHeaders(headers) { // This will have an impact on the compatibility layer for anyone using // non-standard, non-compliant status codes. if (statusCode < 200 || statusCode > 599) - throw new errors.RangeError('ERR_HTTP2_STATUS_INVALID', - headers[HTTP2_HEADER_STATUS]); + throw new ERR_HTTP2_STATUS_INVALID(headers[HTTP2_HEADER_STATUS]); return headers; } @@ -1947,7 +1969,7 @@ function doSendFD(session, options, fd, headers, streamOptions, err, stat) { // In either case, we do not want to continue because the we are shutting // down and should not attempt to send any data. if (this.destroyed || this.closed) { - this.destroy(new errors.Error('ERR_HTTP2_INVALID_STREAM')); + this.destroy(new ERR_HTTP2_INVALID_STREAM()); return; } @@ -1986,7 +2008,7 @@ function doSendFileFD(session, options, fd, headers, streamOptions, err, stat) { } if (!stat.isFile()) { - const err = new errors.Error('ERR_HTTP2_SEND_FILE'); + const err = new ERR_HTTP2_SEND_FILE(); if (onError) onError(err); else @@ -1996,7 +2018,7 @@ function doSendFileFD(session, options, fd, headers, streamOptions, err, stat) { if (this.destroyed || this.closed) { tryClose(fd); - this.destroy(new errors.Error('ERR_HTTP2_INVALID_STREAM')); + this.destroy(new ERR_HTTP2_INVALID_STREAM()); return; } @@ -2079,7 +2101,7 @@ class ServerHttp2Stream extends Http2Stream { // Http2Stream for the push stream. pushStream(headers, options, callback) { if (!this.pushAllowed) - throw new errors.Error('ERR_HTTP2_PUSH_DISABLED'); + throw new ERR_HTTP2_PUSH_DISABLED(); const session = this[kSession]; @@ -2094,7 +2116,7 @@ class ServerHttp2Stream extends Http2Stream { } if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); assertIsObject(options, 'options'); options = Object.assign({}, options); @@ -2128,10 +2150,10 @@ class ServerHttp2Stream extends Http2Stream { if (typeof ret === 'number') { switch (ret) { case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE: - err = new errors.Error('ERR_HTTP2_OUT_OF_STREAMS'); + err = new ERR_HTTP2_OUT_OF_STREAMS(); break; case NGHTTP2_ERR_STREAM_CLOSED: - err = new errors.Error('ERR_HTTP2_INVALID_STREAM'); + err = new ERR_HTTP2_INVALID_STREAM(); break; default: err = new NghttpError(ret); @@ -2157,9 +2179,9 @@ class ServerHttp2Stream extends Http2Stream { // Initiate a response on this Http2Stream respond(headers, options) { if (this.destroyed || this.closed) - throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); + throw new ERR_HTTP2_INVALID_STREAM(); if (this.headersSent) - throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); + throw new ERR_HTTP2_HEADERS_SENT(); const state = this[kState]; @@ -2179,9 +2201,7 @@ class ServerHttp2Stream extends Http2Stream { if (options.getTrailers !== undefined) { if (typeof options.getTrailers !== 'function') { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'getTrailers', - options.getTrailers); + throw new ERR_INVALID_OPT_VALUE('getTrailers', options.getTrailers); } streamOptions |= STREAM_OPTION_GET_TRAILERS; state.getTrailers = options.getTrailers; @@ -2224,9 +2244,9 @@ class ServerHttp2Stream extends Http2Stream { // reset with an error code. respondWithFD(fd, headers, options) { if (this.destroyed || this.closed) - throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); + throw new ERR_HTTP2_INVALID_STREAM(); if (this.headersSent) - throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); + throw new ERR_HTTP2_HEADERS_SENT(); const session = this[kSession]; @@ -2234,36 +2254,27 @@ class ServerHttp2Stream extends Http2Stream { options = Object.assign({}, options); if (options.offset !== undefined && typeof options.offset !== 'number') - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'offset', - options.offset); + throw new ERR_INVALID_OPT_VALUE('offset', options.offset); if (options.length !== undefined && typeof options.length !== 'number') - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'length', - options.length); + throw new ERR_INVALID_OPT_VALUE('length', options.length); if (options.statCheck !== undefined && typeof options.statCheck !== 'function') { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'statCheck', - options.statCheck); + throw new ERR_INVALID_OPT_VALUE('statCheck', options.statCheck); } let streamOptions = 0; if (options.getTrailers !== undefined) { if (typeof options.getTrailers !== 'function') { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'getTrailers', - options.getTrailers); + throw new ERR_INVALID_OPT_VALUE('getTrailers', options.getTrailers); } streamOptions |= STREAM_OPTION_GET_TRAILERS; this[kState].getTrailers = options.getTrailers; } if (typeof fd !== 'number') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'fd', 'number'); + throw new ERR_INVALID_ARG_TYPE('fd', 'number'); debug(`Http2Stream ${this[kID]} [Http2Session ` + `${sessionName(session[kType])}]: initiating response`); @@ -2275,7 +2286,7 @@ class ServerHttp2Stream extends Http2Stream { if (statusCode === HTTP_STATUS_NO_CONTENT || statusCode === HTTP_STATUS_RESET_CONTENT || statusCode === HTTP_STATUS_NOT_MODIFIED) { - throw new errors.Error('ERR_HTTP2_PAYLOAD_FORBIDDEN', statusCode); + throw new ERR_HTTP2_PAYLOAD_FORBIDDEN(statusCode); } if (options.statCheck !== undefined) { @@ -2300,36 +2311,28 @@ class ServerHttp2Stream extends Http2Stream { // file details are sent. respondWithFile(path, headers, options) { if (this.destroyed || this.closed) - throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); + throw new ERR_HTTP2_INVALID_STREAM(); if (this.headersSent) - throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); + throw new ERR_HTTP2_HEADERS_SENT(); assertIsObject(options, 'options'); options = Object.assign({}, options); if (options.offset !== undefined && typeof options.offset !== 'number') - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'offset', - options.offset); + throw new ERR_INVALID_OPT_VALUE('offset', options.offset); if (options.length !== undefined && typeof options.length !== 'number') - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'length', - options.length); + throw new ERR_INVALID_OPT_VALUE('length', options.length); if (options.statCheck !== undefined && typeof options.statCheck !== 'function') { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'statCheck', - options.statCheck); + throw new ERR_INVALID_OPT_VALUE('statCheck', options.statCheck); } let streamOptions = 0; if (options.getTrailers !== undefined) { if (typeof options.getTrailers !== 'function') { - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', - 'getTrailers', - options.getTrailers); + throw new ERR_INVALID_OPT_VALUE('getTrailers', options.getTrailers); } streamOptions |= STREAM_OPTION_GET_TRAILERS; this[kState].getTrailers = options.getTrailers; @@ -2347,7 +2350,7 @@ class ServerHttp2Stream extends Http2Stream { if (statusCode === HTTP_STATUS_NO_CONTENT || statusCode === HTTP_STATUS_RESET_CONTENT || statusCode === HTTP_STATUS_NOT_MODIFIED) { - throw new errors.Error('ERR_HTTP2_PAYLOAD_FORBIDDEN', statusCode); + throw new ERR_HTTP2_PAYLOAD_FORBIDDEN(statusCode); } fs.open(path, 'r', @@ -2363,9 +2366,9 @@ class ServerHttp2Stream extends Http2Stream { // headers are sent, or an error will be thrown. additionalHeaders(headers) { if (this.destroyed || this.closed) - throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); + throw new ERR_HTTP2_INVALID_STREAM(); if (this.headersSent) - throw new errors.Error('ERR_HTTP2_HEADERS_AFTER_RESPOND'); + throw new ERR_HTTP2_HEADERS_AFTER_RESPOND(); assertIsObject(headers, 'headers'); headers = Object.assign(Object.create(null), headers); @@ -2377,10 +2380,9 @@ class ServerHttp2Stream extends Http2Stream { if (headers[HTTP2_HEADER_STATUS] != null) { const statusCode = headers[HTTP2_HEADER_STATUS] |= 0; if (statusCode === HTTP_STATUS_SWITCHING_PROTOCOLS) - throw new errors.Error('ERR_HTTP2_STATUS_101'); + throw new ERR_HTTP2_STATUS_101(); if (statusCode < 100 || statusCode >= 200) { - throw new errors.RangeError('ERR_HTTP2_INVALID_INFO_STATUS', - headers[HTTP2_HEADER_STATUS]); + throw new ERR_HTTP2_INVALID_INFO_STATUS(headers[HTTP2_HEADER_STATUS]); } } @@ -2435,7 +2437,7 @@ const setTimeout = { if (msecs === 0) { if (callback !== undefined) { if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); this.removeListener('timeout', callback); } } else { @@ -2444,7 +2446,7 @@ const setTimeout = { if (callback !== undefined) { if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); this.once('timeout', callback); } } @@ -2589,7 +2591,7 @@ class Http2SecureServer extends TLSServer { this.timeout = msecs; if (callback !== undefined) { if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); this.on('timeout', callback); } return this; @@ -2610,7 +2612,7 @@ class Http2Server extends NETServer { this.timeout = msecs; if (callback !== undefined) { if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); this.on('timeout', callback); } return this; @@ -2632,8 +2634,7 @@ function socketOnClose() { const session = this[kSession]; if (session !== undefined) { debug(`Http2Session ${sessionName(session[kType])}: socket closed`); - const err = session.connecting ? - new errors.Error('ERR_SOCKET_CLOSED') : null; + const err = session.connecting ? new ERR_SOCKET_CLOSED() : null; const state = session[kState]; state.streams.forEach((stream) => stream.close(NGHTTP2_CANCEL)); state.pendingStreams.forEach((stream) => stream.close(NGHTTP2_CANCEL)); @@ -2673,7 +2674,7 @@ function connect(authority, options, listener) { socket = tls.connect(port, host, initializeTLSOptions(options, host)); break; default: - throw new errors.Error('ERR_HTTP2_UNSUPPORTED_PROTOCOL', protocol); + throw new ERR_HTTP2_UNSUPPORTED_PROTOCOL(protocol); } } @@ -2726,11 +2727,10 @@ function getPackedSettings(settings) { function getUnpackedSettings(buf, options = {}) { if (!isArrayBufferView(buf)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'buf', - ['Buffer', 'TypedArray', 'DataView']); + throw new ERR_INVALID_ARG_TYPE('buf', ['Buffer', 'TypedArray', 'DataView']); } if (buf.length % 6 !== 0) - throw new errors.RangeError('ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH'); + throw new ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH(); const settings = {}; let offset = 0; while (offset < buf.length) { diff --git a/lib/internal/http2/util.js b/lib/internal/http2/util.js index 1411ab7cf72ad7..b9bd580af273f6 100644 --- a/lib/internal/http2/util.js +++ b/lib/internal/http2/util.js @@ -1,7 +1,13 @@ 'use strict'; const binding = process.binding('http2'); -const errors = require('internal/errors'); +const { + ERR_HTTP2_HEADER_SINGLE_VALUE, + ERR_HTTP2_INVALID_CONNECTION_HEADERS, + ERR_HTTP2_INVALID_PSEUDOHEADER, + ERR_HTTP2_INVALID_SETTING_VALUE, + ERR_INVALID_ARG_TYPE +} = require('internal/errors').codes; const kSocket = Symbol('socket'); @@ -382,7 +388,7 @@ function isIllegalConnectionSpecificHeader(name, value) { function assertValidPseudoHeader(key) { if (!kValidPseudoHeaders.has(key)) { - const err = new errors.Error('ERR_HTTP2_INVALID_PSEUDOHEADER', key); + const err = new ERR_HTTP2_INVALID_PSEUDOHEADER(key); Error.captureStackTrace(err, assertValidPseudoHeader); return err; } @@ -390,14 +396,14 @@ function assertValidPseudoHeader(key) { function assertValidPseudoHeaderResponse(key) { if (key !== ':status') { - const err = new errors.Error('ERR_HTTP2_INVALID_PSEUDOHEADER', key); + const err = new ERR_HTTP2_INVALID_PSEUDOHEADER(key); Error.captureStackTrace(err, assertValidPseudoHeaderResponse); return err; } } function assertValidPseudoHeaderTrailer(key) { - const err = new errors.Error('ERR_HTTP2_INVALID_PSEUDOHEADER', key); + const err = new ERR_HTTP2_INVALID_PSEUDOHEADER(key); Error.captureStackTrace(err, assertValidPseudoHeaderTrailer); return err; } @@ -426,14 +432,14 @@ function mapToHeaders(map, break; default: if (isSingleValueHeader) - return new errors.Error('ERR_HTTP2_HEADER_SINGLE_VALUE', key); + return new ERR_HTTP2_HEADER_SINGLE_VALUE(key); } } else { value = String(value); } if (isSingleValueHeader) { if (singles.has(key)) - return new errors.Error('ERR_HTTP2_HEADER_SINGLE_VALUE', key); + return new ERR_HTTP2_HEADER_SINGLE_VALUE(key); singles.add(key); } if (key[0] === ':') { @@ -444,7 +450,7 @@ function mapToHeaders(map, count++; } else { if (isIllegalConnectionSpecificHeader(key, value)) { - return new errors.Error('ERR_HTTP2_INVALID_CONNECTION_HEADERS', key); + return new ERR_HTTP2_INVALID_CONNECTION_HEADERS(key); } if (isArray) { for (var k = 0; k < value.length; k++) { @@ -476,7 +482,7 @@ function assertIsObject(value, name, types = 'Object') { (value === null || typeof value !== 'object' || Array.isArray(value))) { - const err = new errors.TypeError('ERR_INVALID_ARG_TYPE', name, types); + const err = new ERR_INVALID_ARG_TYPE(name, types); Error.captureStackTrace(err, assertIsObject); throw err; } @@ -485,8 +491,7 @@ function assertIsObject(value, name, types = 'Object') { function assertWithinRange(name, value, min = 0, max = Infinity) { if (value !== undefined && (typeof value !== 'number' || value < min || value > max)) { - const err = new errors.RangeError('ERR_HTTP2_INVALID_SETTING_VALUE', - name, value); + const err = new ERR_HTTP2_INVALID_SETTING_VALUE.RangeError(name, value); err.min = min; err.max = max; err.actual = value; diff --git a/lib/internal/loader/DefaultResolve.js b/lib/internal/loader/DefaultResolve.js index e92f528721ba3a..c561417bd162c0 100644 --- a/lib/internal/loader/DefaultResolve.js +++ b/lib/internal/loader/DefaultResolve.js @@ -7,7 +7,11 @@ const { NativeModule, internalBinding } = require('internal/bootstrap_loaders'); const { extname } = require('path'); const { realpathSync } = require('fs'); const preserveSymlinks = !!process.binding('config').preserveSymlinks; -const errors = require('internal/errors'); +const { + ERR_MISSING_MODULE, + ERR_MODULE_RESOLUTION_LEGACY, + ERR_UNKNOWN_FILE_EXTENSION +} = require('internal/errors').codes; const { resolve: moduleWrapResolve } = internalBinding('module_wrap'); const StringStartsWith = Function.call.bind(String.prototype.startsWith); const { getURLFromFilePath, getPathFromURL } = require('internal/url'); @@ -17,7 +21,7 @@ const realpathCache = new Map(); function search(target, base) { if (base === undefined) { // We cannot search without a base. - throw new errors.Error('ERR_MISSING_MODULE', target); + throw new ERR_MISSING_MODULE(target); } try { return moduleWrapResolve(target, base); @@ -30,8 +34,7 @@ function search(target, base) { tmpMod.paths = CJSmodule._nodeModulePaths( new URL('./', questionedBase).pathname); const found = CJSmodule._resolveFilename(target, tmpMod); - error = new errors.Error('ERR_MODULE_RESOLUTION_LEGACY', target, - base, found); + error = new ERR_MODULE_RESOLUTION_LEGACY(target, base, found); } catch (problemChecking) { // ignore } @@ -84,7 +87,7 @@ function resolve(specifier, parentURL) { if (isMain) format = 'cjs'; else - throw new errors.Error('ERR_UNKNOWN_FILE_EXTENSION', url.pathname); + throw new ERR_UNKNOWN_FILE_EXTENSION(url.pathname); } return { url: `${url}`, format }; diff --git a/lib/internal/loader/Loader.js b/lib/internal/loader/Loader.js index f0edbbf921f40f..e4457cfd817ba1 100644 --- a/lib/internal/loader/Loader.js +++ b/lib/internal/loader/Loader.js @@ -1,6 +1,11 @@ 'use strict'; -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_PROTOCOL, + ERR_MISSING_DYNAMIC_INTSTANTIATE_HOOK, + ERR_UNKNOWN_MODULE_FORMAT +} = require('internal/errors').codes; const ModuleMap = require('internal/loader/ModuleMap'); const ModuleJob = require('internal/loader/ModuleJob'); const defaultResolve = require('internal/loader/DefaultResolve'); @@ -44,22 +49,22 @@ class Loader { async resolve(specifier, parentURL) { const isMain = parentURL === undefined; if (!isMain && typeof parentURL !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'parentURL', 'string'); + throw new ERR_INVALID_ARG_TYPE('parentURL', 'string'); const { url, format } = await this._resolve(specifier, parentURL, defaultResolve); if (typeof url !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'url', 'string'); + throw new ERR_INVALID_ARG_TYPE('url', 'string'); if (typeof format !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'format', 'string'); + throw new ERR_INVALID_ARG_TYPE('format', 'string'); if (format === 'builtin') return { url: `node:${url}`, format }; if (format !== 'dynamic' && !url.startsWith('file:')) - throw new errors.Error('ERR_INVALID_PROTOCOL', url, 'file:'); + throw new ERR_INVALID_PROTOCOL(url, 'file:'); return { url, format }; } @@ -87,7 +92,7 @@ class Loader { let loaderInstance; if (format === 'dynamic') { if (typeof this._dynamicInstantiate !== 'function') - throw new errors.Error('ERR_MISSING_DYNAMIC_INTSTANTIATE_HOOK'); + throw new ERR_MISSING_DYNAMIC_INTSTANTIATE_HOOK(); loaderInstance = async (url) => { debug(`Translating dynamic ${url}`); @@ -99,7 +104,7 @@ class Loader { }; } else { if (!translators.has(format)) - throw new errors.RangeError('ERR_UNKNOWN_MODULE_FORMAT', format); + throw new ERR_UNKNOWN_MODULE_FORMAT(format); loaderInstance = translators.get(format); } diff --git a/lib/internal/loader/ModuleMap.js b/lib/internal/loader/ModuleMap.js index aa238afbaedc05..dce8f834ba6d10 100644 --- a/lib/internal/loader/ModuleMap.js +++ b/lib/internal/loader/ModuleMap.js @@ -3,29 +3,29 @@ const ModuleJob = require('internal/loader/ModuleJob'); const { SafeMap } = require('internal/safe_globals'); const debug = require('util').debuglog('esm'); -const errors = require('internal/errors'); +const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes; // Tracks the state of the loader-level module cache class ModuleMap extends SafeMap { get(url) { if (typeof url !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'url', 'string'); + throw new ERR_INVALID_ARG_TYPE('url', 'string'); } return super.get(url); } set(url, job) { if (typeof url !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'url', 'string'); + throw new ERR_INVALID_ARG_TYPE('url', 'string'); } if (job instanceof ModuleJob !== true) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'job', 'ModuleJob'); + throw new ERR_INVALID_ARG_TYPE('job', 'ModuleJob'); } debug(`Storing ${url} in ModuleMap`); return super.set(url, job); } has(url) { if (typeof url !== 'string') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'url', 'string'); + throw new ERR_INVALID_ARG_TYPE('url', 'string'); } return super.has(url); } diff --git a/lib/internal/module.js b/lib/internal/module.js index 6e2fb15268ffe4..61565cc5932564 100644 --- a/lib/internal/module.js +++ b/lib/internal/module.js @@ -1,6 +1,6 @@ 'use strict'; -const errors = require('internal/errors'); +const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes; const { CHAR_LINE_FEED, @@ -25,8 +25,7 @@ function makeRequireFunction(mod) { function resolve(request, options) { if (typeof request !== 'string') { - throw new errors.Error('ERR_INVALID_ARG_TYPE', - 'request', 'string', request); + throw new ERR_INVALID_ARG_TYPE('request', 'string', request); } return Module._resolveFilename(request, mod, false, options); } @@ -35,8 +34,7 @@ function makeRequireFunction(mod) { function paths(request) { if (typeof request !== 'string') { - throw new errors.Error('ERR_INVALID_ARG_TYPE', - 'request', 'string', request); + throw new ERR_INVALID_ARG_TYPE('request', 'string', request); } return Module._resolveLookupPaths(request, mod, true); } diff --git a/lib/internal/process.js b/lib/internal/process.js index 3de3ae1603deb5..ba61928adcd6b5 100644 --- a/lib/internal/process.js +++ b/lib/internal/process.js @@ -1,6 +1,16 @@ 'use strict'; -const errors = require('internal/errors'); +const { + errnoException, + codes: { + ERR_ASSERTION, + ERR_CPU_USAGE, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_ARRAY_LENGTH, + ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET, + ERR_UNKNOWN_SIGNAL + } +} = require('internal/errors'); const util = require('util'); const constants = process.binding('constants').os.signals; const assert = require('assert').strict; @@ -8,7 +18,7 @@ const { deprecate } = require('internal/util'); process.assert = deprecate( function(x, msg) { - if (!x) throw new errors.Error('ERR_ASSERTION', msg || 'assertion error'); + if (!x) throw new ERR_ASSERTION(msg || 'assertion error'); }, 'process.assert() is deprecated. Please use the `assert` module instead.', 'DEP0100'); @@ -31,20 +41,18 @@ function setup_cpuUsage() { // If a previous value was passed in, ensure it has the correct shape. if (prevValue) { if (!previousValueIsValid(prevValue.user)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'preValue.user', 'number'); + throw new ERR_INVALID_ARG_TYPE('preValue.user', 'number'); } if (!previousValueIsValid(prevValue.system)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'preValue.system', 'number'); + throw new ERR_INVALID_ARG_TYPE('preValue.system', 'number'); } } // Call the native function to get the current values. const errmsg = _cpuUsage(cpuValues); if (errmsg) { - throw new errors.Error('ERR_CPU_USAGE', errmsg); + throw new ERR_CPU_USAGE(errmsg); } // If a previous value was passed in, return diff of current from previous. @@ -83,12 +91,10 @@ function setup_hrtime() { if (time !== undefined) { if (!Array.isArray(time)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'time', 'Array', - time); + throw new ERR_INVALID_ARG_TYPE('time', 'Array', time); } if (time.length !== 2) { - throw new errors.TypeError('ERR_INVALID_ARRAY_LENGTH', 'time', 2, - time.length); + throw new ERR_INVALID_ARRAY_LENGTH('time', 2, time.length); } const sec = (hrValues[0] * 0x100000000 + hrValues[1]) - time[0]; @@ -158,7 +164,7 @@ function setupKillAndExit() { // eslint-disable-next-line eqeqeq if (pid != (pid | 0)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'pid', 'number'); + throw new ERR_INVALID_ARG_TYPE('pid', 'number'); } // preserve null signal @@ -169,12 +175,12 @@ function setupKillAndExit() { if (constants[sig]) { err = process._kill(pid, constants[sig]); } else { - throw new errors.TypeError('ERR_UNKNOWN_SIGNAL', sig); + throw new ERR_UNKNOWN_SIGNAL(sig); } } if (err) - throw errors.errnoException(err, 'kill'); + throw errnoException(err, 'kill'); return true; }; @@ -204,7 +210,7 @@ function setupSignalHandlers() { const err = wrap.start(signum); if (err) { wrap.close(); - throw errors.errnoException(err, 'uv_signal_start'); + throw errnoException(err, 'uv_signal_start'); } signalWraps[type] = wrap; @@ -256,11 +262,10 @@ function setupUncaughtExceptionCapture(exceptionHandlerState) { return; } if (typeof fn !== 'function') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'fn', - ['Function', 'null']); + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'null']); } if (exceptionHandlerState.captureFn !== null) { - throw new errors.Error('ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET'); + throw new ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET(); } exceptionHandlerState.captureFn = fn; shouldAbortOnUncaughtToggle[0] = 0; diff --git a/lib/internal/process/next_tick.js b/lib/internal/process/next_tick.js index f95d9cc1b82ebf..39e5a6f8124c89 100644 --- a/lib/internal/process/next_tick.js +++ b/lib/internal/process/next_tick.js @@ -17,7 +17,7 @@ function setupNextTick() { symbols: { async_id_symbol, trigger_async_id_symbol } } = require('internal/async_hooks'); const promises = require('internal/process/promises'); - const errors = require('internal/errors'); + const { ERR_INVALID_CALLBACK } = require('internal/errors').codes; const { emitPromiseRejectionWarnings } = promises; // tickInfo is used so that the C++ code in src/node.cc can @@ -146,7 +146,7 @@ function setupNextTick() { // exit since the callback would not have a chance to be executed. function nextTick(callback) { if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); if (process._exiting) return; @@ -170,7 +170,7 @@ function setupNextTick() { // about to exit since the callback would not have a chance to be executed. function internalNextTick(triggerAsyncId, callback) { if (typeof callback !== 'function') - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); // CHECK(Number.isSafeInteger(triggerAsyncId) || triggerAsyncId === null) // CHECK(triggerAsyncId > 0 || triggerAsyncId === null) diff --git a/lib/internal/process/stdio.js b/lib/internal/process/stdio.js index 45568ae631698b..29aee7d09bdab9 100644 --- a/lib/internal/process/stdio.js +++ b/lib/internal/process/stdio.js @@ -1,6 +1,11 @@ 'use strict'; -const errors = require('internal/errors'); +const { + ERR_STDERR_CLOSE, + ERR_STDOUT_CLOSE, + ERR_UNKNOWN_STDIN_TYPE, + ERR_UNKNOWN_STREAM_TYPE +} = require('internal/errors').codes; exports.setup = setupStdio; @@ -15,7 +20,7 @@ function setupStdio() { stdout.destroySoon = stdout.destroy; stdout._destroy = function(er, cb) { // Avoid errors if we already emitted - er = er || new errors.Error('ERR_STDOUT_CLOSE'); + er = er || new ERR_STDOUT_CLOSE(); cb(er); }; if (stdout.isTTY) { @@ -30,7 +35,7 @@ function setupStdio() { stderr.destroySoon = stderr.destroy; stderr._destroy = function(er, cb) { // Avoid errors if we already emitted - er = er || new errors.Error('ERR_STDERR_CLOSE'); + er = er || new ERR_STDERR_CLOSE(); cb(er); }; if (stderr.isTTY) { @@ -87,7 +92,7 @@ function setupStdio() { default: // Probably an error on in uv_guess_handle() - throw new errors.Error('ERR_UNKNOWN_STDIN_TYPE'); + throw new ERR_UNKNOWN_STDIN_TYPE(); } // For supporting legacy API we put the FD here. @@ -171,7 +176,7 @@ function createWritableStdioStream(fd) { default: // Probably an error on in uv_guess_handle() - throw new errors.Error('ERR_UNKNOWN_STREAM_TYPE'); + throw new ERR_UNKNOWN_STREAM_TYPE(); } // For supporting legacy API we put the FD here. diff --git a/lib/internal/process/warning.js b/lib/internal/process/warning.js index 67a3113f2330f4..df2d0c103b0092 100644 --- a/lib/internal/process/warning.js +++ b/lib/internal/process/warning.js @@ -2,7 +2,7 @@ const config = process.binding('config'); const prefix = `(${process.release.name}:${process.pid}) `; -const errors = require('internal/errors'); +const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes; exports.setup = setupProcessWarnings; @@ -122,9 +122,9 @@ function setupProcessWarnings() { code = undefined; } if (code !== undefined && typeof code !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'code', 'string'); + throw new ERR_INVALID_ARG_TYPE('code', 'string'); if (type !== undefined && typeof type !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'type', 'string'); + throw new ERR_INVALID_ARG_TYPE('type', 'string'); if (warning === undefined || typeof warning === 'string') { warning = new Error(warning); warning.name = String(type || 'Warning'); @@ -133,8 +133,7 @@ function setupProcessWarnings() { Error.captureStackTrace(warning, ctor || process.emitWarning); } if (!(warning instanceof Error)) { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'warning', ['Error', 'string']); + throw new ERR_INVALID_ARG_TYPE('warning', ['Error', 'string']); } if (warning.name === 'DeprecationWarning') { if (process.noDeprecation) diff --git a/lib/internal/socket_list.js b/lib/internal/socket_list.js index dd30e9450950e2..55077af1305121 100644 --- a/lib/internal/socket_list.js +++ b/lib/internal/socket_list.js @@ -1,6 +1,6 @@ 'use strict'; -const errors = require('internal/errors'); +const { ERR_CHILD_CLOSED_BEFORE_REPLY } = require('internal/errors').codes; const EventEmitter = require('events'); @@ -21,7 +21,7 @@ class SocketListSend extends EventEmitter { function onclose() { self.child.removeListener('internalMessage', onreply); - callback(new errors.Error('ERR_CHILD_CLOSED_BEFORE_REPLY')); + callback(new ERR_CHILD_CLOSED_BEFORE_REPLY()); } function onreply(msg) { diff --git a/lib/internal/streams/state.js b/lib/internal/streams/state.js index cca79c93de49b5..4a1b49d25cadba 100644 --- a/lib/internal/streams/state.js +++ b/lib/internal/streams/state.js @@ -1,18 +1,18 @@ 'use strict'; -const errors = require('internal/errors'); +const { ERR_INVALID_OPT_VALUE } = require('internal/errors').codes; function getHighWaterMark(state, options, duplexKey, isDuplex) { let hwm = options.highWaterMark; if (hwm != null) { if (typeof hwm !== 'number' || !(hwm >= 0)) - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'highWaterMark', hwm); + throw new ERR_INVALID_OPT_VALUE('highWaterMark', hwm); return Math.floor(hwm); } else if (isDuplex) { hwm = options[duplexKey]; if (hwm != null) { if (typeof hwm !== 'number' || !(hwm >= 0)) - throw new errors.TypeError('ERR_INVALID_OPT_VALUE', duplexKey, hwm); + throw new ERR_INVALID_OPT_VALUE(duplexKey, hwm); return Math.floor(hwm); } } diff --git a/lib/internal/timers.js b/lib/internal/timers.js index 8c1a87a65f4725..26fc3f941bb5f9 100644 --- a/lib/internal/timers.js +++ b/lib/internal/timers.js @@ -10,7 +10,11 @@ const { const async_id_symbol = Symbol('asyncId'); const trigger_async_id_symbol = Symbol('triggerId'); -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CALLBACK, + ERR_OUT_OF_RANGE +} = require('internal/errors').codes; // Timeout values > TIMEOUT_MAX are set to 1. const TIMEOUT_MAX = 2 ** 31 - 1; @@ -94,7 +98,7 @@ Timeout.prototype[refreshFnSymbol] = function refresh() { function setUnrefTimeout(callback, after, arg1, arg2, arg3) { // Type checking identical to setTimeout() if (typeof callback !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } let i, args; @@ -127,13 +131,11 @@ function setUnrefTimeout(callback, after, arg1, arg2, arg3) { // Type checking used by timers.enroll() and Socket#setTimeout() function validateTimerDuration(msecs) { if (typeof msecs !== 'number') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'msecs', - 'number', msecs); + throw new ERR_INVALID_ARG_TYPE('msecs', 'number', msecs); } if (msecs < 0 || !isFinite(msecs)) { - throw new errors.RangeError('ERR_OUT_OF_RANGE', 'msecs', - 'a non-negative finite number', msecs); + throw new ERR_OUT_OF_RANGE('msecs', 'a non-negative finite number', msecs); } // Ensure that msecs fits into signed int32 diff --git a/lib/internal/url.js b/lib/internal/url.js index 0bdfc4783e65f3..842d26c4aac9b6 100644 --- a/lib/internal/url.js +++ b/lib/internal/url.js @@ -7,7 +7,18 @@ const { } = require('internal/querystring'); const { getConstructorOf, removeColors } = require('internal/util'); -const errors = require('internal/errors'); +const { + ERR_ARG_NOT_ITERABLE, + ERR_INVALID_ARG_TYPE, + ERR_INVALID_CALLBACK, + ERR_INVALID_FILE_URL_HOST, + ERR_INVALID_FILE_URL_PATH, + ERR_INVALID_THIS, + ERR_INVALID_TUPLE, + ERR_INVALID_URL, + ERR_INVALID_URL_SCHEME, + ERR_MISSING_ARGS +} = require('internal/errors').codes; const querystring = require('querystring'); const { platform } = process; @@ -107,7 +118,7 @@ class URLSearchParams { this[searchParams] = childParams.slice(); } else if (method !== null && method !== undefined) { if (typeof method !== 'function') { - throw new errors.TypeError('ERR_ARG_NOT_ITERABLE', 'Query pairs'); + throw new ERR_ARG_NOT_ITERABLE('Query pairs'); } // sequence> @@ -117,8 +128,7 @@ class URLSearchParams { if ((typeof pair !== 'object' && typeof pair !== 'function') || pair === null || typeof pair[Symbol.iterator] !== 'function') { - throw new errors.TypeError('ERR_INVALID_TUPLE', 'Each query pair', - '[name, value]'); + throw new ERR_INVALID_TUPLE('Each query pair', '[name, value]'); } const convertedPair = []; for (const element of pair) @@ -129,8 +139,7 @@ class URLSearchParams { this[searchParams] = []; for (const pair of pairs) { if (pair.length !== 2) { - throw new errors.TypeError('ERR_INVALID_TUPLE', 'Each query pair', - '[name, value]'); + throw new ERR_INVALID_TUPLE('Each query pair', '[name, value]'); } this[searchParams].push(pair[0], pair[1]); } @@ -162,7 +171,7 @@ class URLSearchParams { [util.inspect.custom](recurseTimes, ctx) { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } if (typeof recurseTimes === 'number' && recurseTimes < 0) @@ -214,7 +223,7 @@ function onParseComplete(flags, protocol, username, password, } function onParseError(flags, input) { - const error = new errors.TypeError('ERR_INVALID_URL', input); + const error = new ERR_INVALID_URL(input); error.input = input; throw error; } @@ -328,7 +337,7 @@ class URL { [util.inspect.custom](depth, opts) { if (this == null || Object.getPrototypeOf(this[context]) !== URLContext.prototype) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URL'); + throw new ERR_INVALID_THIS('URL'); } if (typeof depth === 'number' && depth < 0) @@ -370,7 +379,7 @@ Object.defineProperties(URL.prototype, { // eslint-disable-next-line func-name-matching value: function format(options) { if (options && typeof options !== 'object') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object'); + throw new ERR_INVALID_ARG_TYPE('options', 'Object'); options = util._extend({ fragment: true, unicode: false, @@ -943,10 +952,10 @@ function merge(out, start, mid, end, lBuffer, rBuffer) { defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { append(name, value) { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } if (arguments.length < 2) { - throw new errors.TypeError('ERR_MISSING_ARGS', 'name', 'value'); + throw new ERR_MISSING_ARGS('name', 'value'); } name = toUSVString(name); @@ -957,10 +966,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { delete(name) { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } if (arguments.length < 1) { - throw new errors.TypeError('ERR_MISSING_ARGS', 'name'); + throw new ERR_MISSING_ARGS('name'); } const list = this[searchParams]; @@ -978,10 +987,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { get(name) { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } if (arguments.length < 1) { - throw new errors.TypeError('ERR_MISSING_ARGS', 'name'); + throw new ERR_MISSING_ARGS('name'); } const list = this[searchParams]; @@ -996,10 +1005,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { getAll(name) { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } if (arguments.length < 1) { - throw new errors.TypeError('ERR_MISSING_ARGS', 'name'); + throw new ERR_MISSING_ARGS('name'); } const list = this[searchParams]; @@ -1015,10 +1024,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { has(name) { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } if (arguments.length < 1) { - throw new errors.TypeError('ERR_MISSING_ARGS', 'name'); + throw new ERR_MISSING_ARGS('name'); } const list = this[searchParams]; @@ -1033,10 +1042,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { set(name, value) { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } if (arguments.length < 2) { - throw new errors.TypeError('ERR_MISSING_ARGS', 'name', 'value'); + throw new ERR_MISSING_ARGS('name', 'value'); } const list = this[searchParams]; @@ -1120,7 +1129,7 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { // must be set to `entries`. entries() { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } return createSearchParamsIterator(this, 'key+value'); @@ -1128,10 +1137,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { forEach(callback, thisArg = undefined) { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } if (typeof callback !== 'function') { - throw new errors.TypeError('ERR_INVALID_CALLBACK'); + throw new ERR_INVALID_CALLBACK(); } let list = this[searchParams]; @@ -1150,7 +1159,7 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { // https://heycam.github.io/webidl/#es-iterable keys() { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } return createSearchParamsIterator(this, 'key'); @@ -1158,7 +1167,7 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { values() { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } return createSearchParamsIterator(this, 'value'); @@ -1168,7 +1177,7 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { // https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior toString() { if (!this || !this[searchParams] || this[searchParams][searchParams]) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParams'); + throw new ERR_INVALID_THIS('URLSearchParams'); } return serializeParams(this[searchParams]); @@ -1200,7 +1209,7 @@ defineIDLClass(URLSearchParamsIteratorPrototype, 'URLSearchParams Iterator', { next() { if (!this || Object.getPrototypeOf(this) !== URLSearchParamsIteratorPrototype) { - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParamsIterator'); + throw new ERR_INVALID_THIS('URLSearchParamsIterator'); } const { @@ -1237,7 +1246,7 @@ defineIDLClass(URLSearchParamsIteratorPrototype, 'URLSearchParams Iterator', { }, [util.inspect.custom](recurseTimes, ctx) { if (this == null || this[context] == null || this[context].target == null) - throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParamsIterator'); + throw new ERR_INVALID_THIS('URLSearchParamsIterator'); if (typeof recurseTimes === 'number' && recurseTimes < 0) return ctx.stylize('[Object]', 'special'); @@ -1276,7 +1285,7 @@ defineIDLClass(URLSearchParamsIteratorPrototype, 'URLSearchParams Iterator', { function domainToASCII(domain) { if (arguments.length < 1) - throw new errors.TypeError('ERR_MISSING_ARGS', 'domain'); + throw new ERR_MISSING_ARGS('domain'); // toUSVString is not needed. return _domainToASCII(`${domain}`); @@ -1284,7 +1293,7 @@ function domainToASCII(domain) { function domainToUnicode(domain) { if (arguments.length < 1) - throw new errors.TypeError('ERR_MISSING_ARGS', 'domain'); + throw new ERR_MISSING_ARGS('domain'); // toUSVString is not needed. return _domainToUnicode(`${domain}`); @@ -1320,9 +1329,9 @@ function getPathFromURLWin32(url) { var third = pathname.codePointAt(n + 2) | 0x20; if ((pathname[n + 1] === '2' && third === 102) || // 2f 2F / (pathname[n + 1] === '5' && third === 99)) { // 5c 5C \ - throw new errors.TypeError( - 'ERR_INVALID_FILE_URL_PATH', - 'must not include encoded \\ or / characters'); + throw new ERR_INVALID_FILE_URL_PATH( + 'must not include encoded \\ or / characters' + ); } } } @@ -1341,8 +1350,7 @@ function getPathFromURLWin32(url) { var sep = pathname[2]; if (letter < 97 || letter > 122 || // a..z A..Z (sep !== ':')) { - throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', - 'must be absolute'); + throw new ERR_INVALID_FILE_URL_PATH('must be absolute'); } return pathname.slice(1); } @@ -1350,15 +1358,16 @@ function getPathFromURLWin32(url) { function getPathFromURLPosix(url) { if (url.hostname !== '') { - throw new errors.TypeError('ERR_INVALID_FILE_URL_HOST', platform); + throw new ERR_INVALID_FILE_URL_HOST(platform); } var pathname = url.pathname; for (var n = 0; n < pathname.length; n++) { if (pathname[n] === '%') { var third = pathname.codePointAt(n + 2) | 0x20; if (pathname[n + 1] === '2' && third === 102) { - throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', - 'must not include encoded / characters'); + throw new ERR_INVALID_FILE_URL_PATH( + 'must not include encoded / characters' + ); } } } @@ -1371,7 +1380,7 @@ function getPathFromURL(path) { return path; } if (path.protocol !== 'file:') - throw new errors.TypeError('ERR_INVALID_URL_SCHEME', 'file'); + throw new ERR_INVALID_URL_SCHEME('file'); return isWindows ? getPathFromURLWin32(path) : getPathFromURLPosix(path); } diff --git a/lib/internal/util.js b/lib/internal/util.js index 6a4cf7ee2ae91d..d044f32ca5f685 100644 --- a/lib/internal/util.js +++ b/lib/internal/util.js @@ -1,6 +1,10 @@ 'use strict'; -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_NO_CRYPTO, + ERR_UNKNOWN_SIGNAL +} = require('internal/errors').codes; const { signals } = process.binding('constants').os; const { @@ -45,7 +49,7 @@ function deprecate(fn, msg, code) { } if (code !== undefined && typeof code !== 'string') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'code', 'string'); + throw new ERR_INVALID_ARG_TYPE('code', 'string'); let warned = false; function deprecated(...args) { @@ -93,7 +97,7 @@ function decorateErrorStack(err) { function assertCrypto() { if (noCrypto) - throw new errors.Error('ERR_NO_CRYPTO'); + throw new ERR_NO_CRYPTO(); } // Return undefined if there is no match. @@ -225,7 +229,7 @@ function convertToValidSignal(signal) { if (signalName) return signalName; } - throw new errors.TypeError('ERR_UNKNOWN_SIGNAL', signal); + throw new ERR_UNKNOWN_SIGNAL(signal); } function getConstructorOf(obj) { @@ -290,15 +294,12 @@ const kCustomPromisifyArgsSymbol = Symbol('customPromisifyArgs'); function promisify(original) { if (typeof original !== 'function') - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'original', 'Function'); + throw new ERR_INVALID_ARG_TYPE('original', 'Function'); if (original[kCustomPromisifiedSymbol]) { const fn = original[kCustomPromisifiedSymbol]; if (typeof fn !== 'function') { - throw new errors.TypeError('ERR_INVALID_ARG_TYPE', - 'util.promisify.custom', - 'Function', - fn); + throw new ERR_INVALID_ARG_TYPE('util.promisify.custom', 'Function', fn); } Object.defineProperty(fn, kCustomPromisifiedSymbol, { value: fn, enumerable: false, writable: false, configurable: true diff --git a/lib/internal/vm/Module.js b/lib/internal/vm/Module.js index e954babf1df5af..6d8f7f76d8354b 100644 --- a/lib/internal/vm/Module.js +++ b/lib/internal/vm/Module.js @@ -4,7 +4,15 @@ const { internalBinding } = require('internal/bootstrap_loaders'); const { emitExperimentalWarning } = require('internal/util'); const { URL } = require('internal/url'); const { kParsingContext, isContext } = process.binding('contextify'); -const errors = require('internal/errors'); +const { + ERR_INVALID_ARG_TYPE, + ERR_VM_MODULE_ALREADY_LINKED, + ERR_VM_MODULE_DIFFERENT_CONTEXT, + ERR_VM_MODULE_LINKING_ERRORED, + ERR_VM_MODULE_NOT_LINKED, + ERR_VM_MODULE_NOT_MODULE, + ERR_VM_MODULE_STATUS +} = require('internal/errors').codes; const { getConstructorOf, customInspectSymbol, @@ -41,27 +49,23 @@ class Module { emitExperimentalWarning('vm.Module'); if (typeof src !== 'string') - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'src', 'string', src); + throw new ERR_INVALID_ARG_TYPE('src', 'string', src); 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); let context; if (options.context !== undefined) { if (isContext(options.context)) { context = options.context; } else { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'options.context', 'vm.Context'); + throw new ERR_INVALID_ARG_TYPE('options.context', 'vm.Context'); } } let url = options.url; if (url !== undefined) { if (typeof url !== 'string') { - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'options.url', 'string', url); + throw new ERR_INVALID_ARG_TYPE('options.url', 'string', url); } url = new URL(url).href; } else if (context === undefined) { @@ -101,8 +105,9 @@ class Module { get namespace() { const wrap = wrapMap.get(this); if (wrap.getStatus() < kInstantiated) - throw new errors.Error('ERR_VM_MODULE_STATUS', - 'must not be uninstantiated or instantiating'); + throw new ERR_VM_MODULE_STATUS( + 'must not be uninstantiated or instantiating' + ); return wrap.namespace(); } @@ -120,31 +125,30 @@ class Module { get error() { const wrap = wrapMap.get(this); if (wrap.getStatus() !== kErrored) - throw new errors.Error('ERR_VM_MODULE_STATUS', 'must be errored'); + throw new ERR_VM_MODULE_STATUS('must be errored'); return wrap.getError(); } async link(linker) { if (typeof linker !== 'function') - throw new errors.TypeError( - 'ERR_INVALID_ARG_TYPE', 'linker', 'function', linker); + throw new ERR_INVALID_ARG_TYPE('linker', 'function', linker); if (linkingStatusMap.get(this) !== 'unlinked') - throw new errors.Error('ERR_VM_MODULE_ALREADY_LINKED'); + throw new ERR_VM_MODULE_ALREADY_LINKED(); const wrap = wrapMap.get(this); if (wrap.getStatus() !== kUninstantiated) - throw new errors.Error('ERR_VM_MODULE_STATUS', 'must be uninstantiated'); + throw new ERR_VM_MODULE_STATUS('must be uninstantiated'); linkingStatusMap.set(this, 'linking'); const promises = wrap.link(async (specifier) => { const m = await linker(specifier, this); if (!m || !wrapMap.has(m)) - throw new errors.Error('ERR_VM_MODULE_NOT_MODULE'); + throw new ERR_VM_MODULE_NOT_MODULE(); if (m.context !== this.context) - throw new errors.Error('ERR_VM_MODULE_DIFFERENT_CONTEXT'); + throw new ERR_VM_MODULE_DIFFERENT_CONTEXT(); const childLinkingStatus = linkingStatusMap.get(m); if (childLinkingStatus === 'errored') - throw new errors.Error('ERR_VM_MODULE_LINKING_ERRORED'); + throw new ERR_VM_MODULE_LINKING_ERRORED(); if (childLinkingStatus === 'unlinked') await m.link(linker); return wrapMap.get(m); @@ -164,10 +168,9 @@ class Module { const wrap = wrapMap.get(this); const status = wrap.getStatus(); if (status === kInstantiating || status === kEvaluating) - throw new errors.Error( - 'ERR_VM_MODULE_STATUS', 'must not be instantiating or evaluating'); + throw new ERR_VM_MODULE_STATUS('must not be instantiating or evaluating'); if (linkingStatusMap.get(this) !== 'linked') - throw new errors.Error('ERR_VM_MODULE_NOT_LINKED'); + throw new ERR_VM_MODULE_NOT_LINKED(); wrap.instantiate(); } @@ -177,9 +180,9 @@ class Module { if (status !== kInstantiated && status !== kEvaluated && status !== kErrored) { - throw new errors.Error( - 'ERR_VM_MODULE_STATUS', - 'must be one of instantiated, evaluated, and errored'); + throw new ERR_VM_MODULE_STATUS( + 'must be one of instantiated, evaluated, and errored' + ); } const result = wrap.evaluate(options); return { result, __proto__: null }; diff --git a/lib/internal/wrap_js_stream.js b/lib/internal/wrap_js_stream.js index feacab267bea4d..9a7e9cd48ab3e8 100644 --- a/lib/internal/wrap_js_stream.js +++ b/lib/internal/wrap_js_stream.js @@ -6,7 +6,7 @@ const { Socket } = require('net'); const { JSStream } = process.binding('js_stream'); const uv = process.binding('uv'); const debug = util.debuglog('stream_wrap'); -const errors = require('internal/errors'); +const { ERR_STREAM_WRAP } = require('internal/errors').codes; const kCurrentWriteRequest = Symbol('kCurrentWriteRequest'); const kCurrentShutdownRequest = Symbol('kCurrentShutdownRequest'); @@ -53,7 +53,7 @@ class JSStreamWrap extends Socket { stream.pause(); stream.removeListener('data', ondata); - this.emit('error', new errors.Error('ERR_STREAM_WRAP')); + this.emit('error', new ERR_STREAM_WRAP()); return; } diff --git a/test/es-module/test-esm-loader-search.js b/test/es-module/test-esm-loader-search.js index 4eb6b9fd4b3889..4a85ea93253a0c 100644 --- a/test/es-module/test-esm-loader-search.js +++ b/test/es-module/test-esm-loader-search.js @@ -6,13 +6,12 @@ const common = require('../common'); const { search } = require('internal/loader/DefaultResolve'); -const errors = require('internal/errors'); common.expectsError( () => search('target', undefined), { code: 'ERR_MISSING_MODULE', - type: errors.Error, + type: Error, message: 'Cannot find module target' } ); diff --git a/test/parallel/test-fs-null-bytes.js b/test/parallel/test-fs-null-bytes.js index 6ffaef571ac8d6..c409e6f4884353 100644 --- a/test/parallel/test-fs-null-bytes.js +++ b/test/parallel/test-fs-null-bytes.js @@ -36,7 +36,7 @@ function check(async, sync) { }, { code: 'ERR_INVALID_ARG_VALUE', - type: Error, + type: TypeError, }); } @@ -47,7 +47,7 @@ function check(async, sync) { }, { code: 'ERR_INVALID_ARG_VALUE', - type: Error + type: TypeError }); } } diff --git a/test/parallel/test-fs-whatwg-url.js b/test/parallel/test-fs-whatwg-url.js index cfdfbe0dde01b8..159fc0cc1b31ea 100644 --- a/test/parallel/test-fs-whatwg-url.js +++ b/test/parallel/test-fs-whatwg-url.js @@ -61,7 +61,7 @@ if (common.isWindows) { }, { code: 'ERR_INVALID_ARG_VALUE', - type: Error, + type: TypeError, message: 'The argument \'path\' must be a string or Uint8Array without ' + 'null bytes. Received \'c:/tmp/\\u0000test\'' } @@ -95,7 +95,7 @@ if (common.isWindows) { }, { code: 'ERR_INVALID_ARG_VALUE', - type: Error, + type: TypeError, message: 'The argument \'path\' must be a string or Uint8Array without ' + 'null bytes. Received \'/tmp/\\u0000test\'' }