lib: port remaining errors to new system

PR-URL: https://github.com/nodejs/node/pull/19137
Reviewed-By: Anatoli Papirovski <apapirovski@mac.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Joyee Cheung <joyeec9h3@gmail.com>
This commit is contained in:
Michaël Zasso 2018-03-04 22:16:24 +01:00
parent cb5f9a6d87
commit 1d2fd8b65b
44 changed files with 761 additions and 615 deletions

View File

@ -39,15 +39,23 @@ const { Buffer } = require('buffer');
const { urlToOptions, searchParamsSymbol } = require('internal/url'); const { urlToOptions, searchParamsSymbol } = require('internal/url');
const { outHeadersKey, ondrain } = require('internal/http'); const { outHeadersKey, ondrain } = require('internal/http');
const { nextTick } = require('internal/process/next_tick'); 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 { validateTimerDuration } = require('internal/timers');
const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/; const INVALID_PATH_REGEX = /[^\u0021-\u00ff]/;
function validateHost(host, name) { function validateHost(host, name) {
if (host !== null && host !== undefined && typeof host !== 'string') { if (host !== null && host !== undefined && typeof host !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', `options.${name}`, throw new ERR_INVALID_ARG_TYPE(`options.${name}`,
['string', 'undefined', 'null'], host); ['string', 'undefined', 'null'],
host);
} }
return host; return host;
} }
@ -58,7 +66,7 @@ function ClientRequest(options, cb) {
if (typeof options === 'string') { if (typeof options === 'string') {
options = url.parse(options); options = url.parse(options);
if (!options.hostname) { if (!options.hostname) {
throw new errors.Error('ERR_INVALID_DOMAIN_NAME'); throw new ERR_INVALID_DOMAIN_NAME();
} }
} else if (options && options[searchParamsSymbol] && } else if (options && options[searchParamsSymbol] &&
options[searchParamsSymbol][searchParamsSymbol]) { options[searchParamsSymbol][searchParamsSymbol]) {
@ -79,8 +87,8 @@ function ClientRequest(options, cb) {
// Explicitly pass through this statement as agent will not be used // Explicitly pass through this statement as agent will not be used
// when createConnection is provided. // when createConnection is provided.
} else if (typeof agent.addRequest !== 'function') { } else if (typeof agent.addRequest !== 'function') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'Agent option', throw new ERR_INVALID_ARG_TYPE('Agent option',
['Agent-like Object', 'undefined', 'false']); ['Agent-like Object', 'undefined', 'false']);
} }
this.agent = agent; this.agent = agent;
@ -93,11 +101,11 @@ function ClientRequest(options, cb) {
if (options.path) { if (options.path) {
path = String(options.path); path = String(options.path);
if (INVALID_PATH_REGEX.test(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) { if (protocol !== expectedProtocol) {
throw new errors.Error('ERR_INVALID_PROTOCOL', protocol, expectedProtocol); throw new ERR_INVALID_PROTOCOL(protocol, expectedProtocol);
} }
var defaultPort = options.defaultPort || var defaultPort = options.defaultPort ||
@ -115,13 +123,12 @@ function ClientRequest(options, cb) {
var method = options.method; var method = options.method;
var methodIsString = (typeof method === 'string'); var methodIsString = (typeof method === 'string');
if (method !== null && method !== undefined && !methodIsString) { if (method !== null && method !== undefined && !methodIsString) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'method', throw new ERR_INVALID_ARG_TYPE('method', 'string', method);
'string', method);
} }
if (methodIsString && method) { if (methodIsString && method) {
if (!checkIsHttpToken(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(); method = this.method = method.toUpperCase();
} else { } else {
@ -203,7 +210,7 @@ function ClientRequest(options, cb) {
if (this.getHeader('expect')) { if (this.getHeader('expect')) {
if (this._header) { 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._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n',
@ -261,7 +268,7 @@ ClientRequest.prototype._finish = function _finish() {
ClientRequest.prototype._implicitHeader = function _implicitHeader() { ClientRequest.prototype._implicitHeader = function _implicitHeader() {
if (this._header) { 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._storeHeader(this.method + ' ' + this.path + ' HTTP/1.1\r\n',
this[outHeadersKey]); this[outHeadersKey]);

View File

@ -33,7 +33,17 @@ const checkInvalidHeaderChar = common._checkInvalidHeaderChar;
const { outHeadersKey } = require('internal/http'); const { outHeadersKey } = require('internal/http');
const { async_id_symbol } = require('internal/async_hooks').symbols; const { async_id_symbol } = require('internal/async_hooks').symbols;
const { nextTick } = require('internal/process/next_tick'); 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 { CRLF, debug } = common;
const { utcDate } = internalHttp; const { utcDate } = internalHttp;
@ -165,7 +175,7 @@ Object.defineProperty(OutgoingMessage.prototype, '_headerNames', {
OutgoingMessage.prototype._renderHeaders = function _renderHeaders() { OutgoingMessage.prototype._renderHeaders = function _renderHeaders() {
if (this._header) { if (this._header) {
throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'render'); throw new ERR_HTTP_HEADERS_SENT('render');
} }
var headersMap = this[outHeadersKey]; var headersMap = this[outHeadersKey];
@ -424,7 +434,7 @@ function _storeHeader(firstLine, headers) {
// header fields, regardless of the header fields present in the // header fields, regardless of the header fields present in the
// message, and thus cannot contain a message body or 'trailers'. // message, and thus cannot contain a message body or 'trailers'.
if (this.chunkedEncoding !== true && state.trailer) { 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; this._header = state.header + CRLF;
@ -488,12 +498,12 @@ function matchHeader(self, state, field, value) {
function validateHeader(name, value) { function validateHeader(name, value) {
let err; let err;
if (typeof name !== 'string' || !name || !checkIsHttpToken(name)) { 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) { } 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)) { } else if (checkInvalidHeaderChar(value)) {
debug('Header "%s" contains invalid characters', name); 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) { if (err !== undefined) {
Error.captureStackTrace(err, validateHeader); Error.captureStackTrace(err, validateHeader);
@ -503,7 +513,7 @@ function validateHeader(name, value) {
OutgoingMessage.prototype.setHeader = function setHeader(name, value) { OutgoingMessage.prototype.setHeader = function setHeader(name, value) {
if (this._header) { if (this._header) {
throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'set'); throw new ERR_HTTP_HEADERS_SENT('set');
} }
validateHeader(name, value); validateHeader(name, value);
@ -529,7 +539,7 @@ OutgoingMessage.prototype.setHeader = function setHeader(name, value) {
OutgoingMessage.prototype.getHeader = function getHeader(name) { OutgoingMessage.prototype.getHeader = function getHeader(name) {
if (typeof name !== 'string') { 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; if (!this[outHeadersKey]) return;
@ -565,7 +575,7 @@ OutgoingMessage.prototype.getHeaders = function getHeaders() {
OutgoingMessage.prototype.hasHeader = function hasHeader(name) { OutgoingMessage.prototype.hasHeader = function hasHeader(name) {
if (typeof name !== 'string') { 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()]); return !!(this[outHeadersKey] && this[outHeadersKey][name.toLowerCase()]);
@ -574,11 +584,11 @@ OutgoingMessage.prototype.hasHeader = function hasHeader(name) {
OutgoingMessage.prototype.removeHeader = function removeHeader(name) { OutgoingMessage.prototype.removeHeader = function removeHeader(name) {
if (typeof name !== 'string') { 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) { if (this._header) {
throw new errors.Error('ERR_HTTP_HEADERS_SENT', 'remove'); throw new ERR_HTTP_HEADERS_SENT('remove');
} }
var key = name.toLowerCase(); var key = name.toLowerCase();
@ -605,7 +615,7 @@ OutgoingMessage.prototype.removeHeader = function removeHeader(name) {
OutgoingMessage.prototype._implicitHeader = function _implicitHeader() { 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', { Object.defineProperty(OutgoingMessage.prototype, 'headersSent', {
@ -622,7 +632,7 @@ OutgoingMessage.prototype.write = function write(chunk, encoding, callback) {
function write_(msg, chunk, encoding, callback, fromEnd) { function write_(msg, chunk, encoding, callback, fromEnd) {
if (msg.finished) { 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], nextTick(msg.socket && msg.socket[async_id_symbol],
writeAfterEndNT.bind(msg), writeAfterEndNT.bind(msg),
err, err,
@ -642,8 +652,7 @@ function write_(msg, chunk, encoding, callback, fromEnd) {
} }
if (!fromEnd && typeof chunk !== 'string' && !(chunk instanceof Buffer)) { if (!fromEnd && typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument', throw new ERR_INVALID_ARG_TYPE('first argument', ['string', 'Buffer']);
['string', 'Buffer']);
} }
@ -711,12 +720,11 @@ OutgoingMessage.prototype.addTrailers = function addTrailers(headers) {
value = headers[key]; value = headers[key];
} }
if (typeof field !== 'string' || !field || !checkIsHttpToken(field)) { if (typeof field !== 'string' || !field || !checkIsHttpToken(field)) {
throw new errors.TypeError('ERR_INVALID_HTTP_TOKEN', 'Trailer name', throw new ERR_INVALID_HTTP_TOKEN('Trailer name', field);
field);
} }
if (checkInvalidHeaderChar(value)) { if (checkInvalidHeaderChar(value)) {
debug('Trailer "%s" contains invalid characters', field); 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; this._trailer += field + ': ' + escapeHeaderValue(value) + CRLF;
} }
@ -742,8 +750,7 @@ OutgoingMessage.prototype.end = function end(chunk, encoding, callback) {
var uncork; var uncork;
if (chunk) { if (chunk) {
if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) { if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'first argument', throw new ERR_INVALID_ARG_TYPE('first argument', ['string', 'Buffer']);
['string', 'Buffer']);
} }
if (!this._header) { if (!this._header) {
if (typeof chunk === 'string') if (typeof chunk === 'string')
@ -874,7 +881,7 @@ OutgoingMessage.prototype.flush = internalUtil.deprecate(function() {
OutgoingMessage.prototype.pipe = function pipe() { OutgoingMessage.prototype.pipe = function pipe() {
// OutgoingMessage should be write-only. Piping from it is disabled. // 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 = { module.exports = {

View File

@ -43,7 +43,11 @@ const {
getOrSetAsyncId getOrSetAsyncId
} = require('internal/async_hooks'); } = require('internal/async_hooks');
const { IncomingMessage } = require('_http_incoming'); 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 Buffer = require('buffer').Buffer;
const kServerResponse = Symbol('ServerResponse'); const kServerResponse = Symbol('ServerResponse');
@ -201,8 +205,7 @@ function writeHead(statusCode, reason, obj) {
statusCode |= 0; statusCode |= 0;
if (statusCode < 100 || statusCode > 999) { if (statusCode < 100 || statusCode > 999) {
throw new errors.RangeError('ERR_HTTP_INVALID_STATUS_CODE', throw new ERR_HTTP_INVALID_STATUS_CODE(originalStatusCode);
originalStatusCode);
} }
@ -229,7 +232,7 @@ function writeHead(statusCode, reason, obj) {
} }
} }
if (k === undefined && this._header) { 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 // only progressive api is used
headers = this[outHeadersKey]; headers = this[outHeadersKey];
@ -239,7 +242,7 @@ function writeHead(statusCode, reason, obj) {
} }
if (checkInvalidHeaderChar(this.statusMessage)) 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}`; var statusLine = `HTTP/1.1 ${statusCode} ${this.statusMessage}${CRLF}`;

View File

@ -32,7 +32,12 @@ const debug = util.debuglog('stream');
const BufferList = require('internal/streams/BufferList'); const BufferList = require('internal/streams/BufferList');
const destroyImpl = require('internal/streams/destroy'); const destroyImpl = require('internal/streams/destroy');
const { getHighWaterMark } = require('internal/streams/state'); 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 ReadableAsyncIterator = require('internal/streams/async_iterator');
const { emitExperimentalWarning } = require('internal/util'); const { emitExperimentalWarning } = require('internal/util');
var StringDecoder; var StringDecoder;
@ -232,12 +237,11 @@ function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
if (addToFront) { if (addToFront) {
if (state.endEmitted) if (state.endEmitted)
stream.emit('error', stream.emit('error', new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());
new errors.Error('ERR_STREAM_UNSHIFT_AFTER_END_EVENT'));
else else
addChunk(stream, state, chunk, true); addChunk(stream, state, chunk, true);
} else if (state.ended) { } 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) { } else if (state.destroyed) {
return false; return false;
} else { } else {
@ -285,8 +289,7 @@ function chunkInvalid(state, chunk) {
typeof chunk !== 'string' && typeof chunk !== 'string' &&
chunk !== undefined && chunk !== undefined &&
!state.objectMode) { !state.objectMode) {
er = new errors.TypeError('ERR_INVALID_ARG_TYPE', er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array']);
'chunk', ['string', 'Buffer', 'Uint8Array']);
} }
return er; return er;
} }
@ -565,7 +568,7 @@ function maybeReadMore_(stream, state) {
// for virtual (non-string, non-buffer) streams, "length" is somewhat // for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful. // arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function(n) { 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) { Readable.prototype.pipe = function(dest, pipeOpts) {

View File

@ -64,7 +64,12 @@
'use strict'; 'use strict';
module.exports = Transform; 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 Duplex = require('_stream_duplex');
const util = require('util'); const util = require('util');
util.inherits(Transform, Duplex); util.inherits(Transform, Duplex);
@ -77,7 +82,7 @@ function afterTransform(er, data) {
var cb = ts.writecb; var cb = ts.writecb;
if (cb === null) { if (cb === null) {
return this.emit('error', new errors.Error('ERR_MULTIPLE_CALLBACK')); return this.emit('error', new ERR_MULTIPLE_CALLBACK());
} }
ts.writechunk = null; 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 // an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk. // never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function(chunk, encoding, cb) { 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) { 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 // if there's nothing in the write buffer, then that means
// that nothing more will ever be provided // that nothing more will ever be provided
if (stream._writableState.length) if (stream._writableState.length)
throw new errors.Error('ERR_TRANSFORM_WITH_LENGTH_0'); throw new ERR_TRANSFORM_WITH_LENGTH_0();
if (stream._transformState.transforming) if (stream._transformState.transforming)
throw new errors.Error('ERR_TRANSFORM_ALREADY_TRANSFORMING'); throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
return stream.push(null); return stream.push(null);
} }

View File

@ -34,7 +34,15 @@ const Stream = require('stream');
const { Buffer } = require('buffer'); const { Buffer } = require('buffer');
const destroyImpl = require('internal/streams/destroy'); const destroyImpl = require('internal/streams/destroy');
const { getHighWaterMark } = require('internal/streams/state'); 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); util.inherits(Writable, Stream);
@ -222,12 +230,12 @@ function Writable(options) {
// Otherwise people can pipe Writable streams, which is just wrong. // Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function() { 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) { 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 // TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er); stream.emit('error', er);
process.nextTick(cb, er); process.nextTick(cb, er);
@ -241,10 +249,9 @@ function validChunk(stream, state, chunk, cb) {
var er = false; var er = false;
if (chunk === null) { if (chunk === null) {
er = new errors.TypeError('ERR_STREAM_NULL_VALUES'); er = new ERR_STREAM_NULL_VALUES();
} else if (typeof chunk !== 'string' && !state.objectMode) { } else if (typeof chunk !== 'string' && !state.objectMode) {
er = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'chunk', er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer']);
['string', 'Buffer']);
} }
if (er) { if (er) {
stream.emit('error', er); stream.emit('error', er);
@ -311,7 +318,7 @@ Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
if (typeof encoding === 'string') if (typeof encoding === 'string')
encoding = encoding.toLowerCase(); encoding = encoding.toLowerCase();
if (!Buffer.isEncoding(encoding)) if (!Buffer.isEncoding(encoding))
throw new errors.TypeError('ERR_UNKNOWN_ENCODING', encoding); throw new ERR_UNKNOWN_ENCODING(encoding);
this._writableState.defaultEncoding = encoding; this._writableState.defaultEncoding = encoding;
return this; return this;
}; };
@ -394,7 +401,7 @@ function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writing = true; state.writing = true;
state.sync = true; state.sync = true;
if (state.destroyed) if (state.destroyed)
state.onwrite(new errors.Error('ERR_STREAM_DESTROYED', 'write')); state.onwrite(new ERR_STREAM_DESTROYED('write'));
else if (writev) else if (writev)
stream._writev(chunk, state.onwrite); stream._writev(chunk, state.onwrite);
else else
@ -546,7 +553,7 @@ function clearBuffer(stream, state) {
} }
Writable.prototype._write = function(chunk, encoding, cb) { 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; Writable.prototype._writev = null;

View File

@ -24,7 +24,10 @@
const { parseCertString } = require('internal/tls'); const { parseCertString } = require('internal/tls');
const { isArrayBufferView } = require('internal/util/types'); const { isArrayBufferView } = require('internal/util/types');
const tls = require('tls'); 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; const { SSL_OP_CIPHER_SERVER_PREFERENCE } = process.binding('constants').crypto;
@ -56,8 +59,8 @@ function SecureContext(secureProtocol, secureOptions, context) {
function validateKeyCert(value, type) { function validateKeyCert(value, type) {
if (typeof value !== 'string' && !isArrayBufferView(value)) if (typeof value !== 'string' && !isArrayBufferView(value))
throw new errors.TypeError( throw new ERR_INVALID_ARG_TYPE(
'ERR_INVALID_ARG_TYPE', type, type,
['string', 'Buffer', 'TypedArray', 'DataView'] ['string', 'Buffer', 'TypedArray', 'DataView']
); );
} }
@ -212,12 +215,11 @@ exports.createSecureContext = function createSecureContext(options, context) {
if (c.context.setClientCertEngine) if (c.context.setClientCertEngine)
c.context.setClientCertEngine(options.clientCertEngine); c.context.setClientCertEngine(options.clientCertEngine);
else else
throw new errors.Error('ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED'); throw new ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED();
} else if (options.clientCertEngine != null) { } else if (options.clientCertEngine != null) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('options.clientCertEngine',
'options.clientCertEngine', ['string', 'null', 'undefined'],
['string', 'null', 'undefined'], options.clientCertEngine);
options.clientCertEngine);
} }
return c; return c;

View File

@ -38,7 +38,18 @@ const { Pipe, constants: PipeConstants } = process.binding('pipe_wrap');
const { const {
SecureContext: NativeSecureContext SecureContext: NativeSecureContext
} = process.binding('crypto'); } = 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 kConnectOptions = Symbol('connect-options');
const kDisableRenegotiation = Symbol('disable-renegotiation'); const kDisableRenegotiation = Symbol('disable-renegotiation');
const kErrorEmitted = Symbol('error-emitted'); const kErrorEmitted = Symbol('error-emitted');
@ -71,12 +82,12 @@ function onhandshakestart(now) {
} }
if (owner[kDisableRenegotiation] && this.handshakes > 0) { 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) { function emitSessionAttackError(socket) {
socket._emitTLSError(new errors.Error('ERR_TLS_SESSION_ATTACK')); socket._emitTLSError(new ERR_TLS_SESSION_ATTACK());
} }
function onhandshakedone() { function onhandshakedone() {
@ -100,14 +111,14 @@ function loadSession(hello) {
var once = false; var once = false;
function onSession(err, session) { function onSession(err, session) {
if (once) if (once)
return owner.destroy(new errors.Error('ERR_MULTIPLE_CALLBACK')); return owner.destroy(new ERR_MULTIPLE_CALLBACK());
once = true; once = true;
if (err) if (err)
return owner.destroy(err); return owner.destroy(err);
if (owner._handle === null) 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.loadSession(session);
owner._handle.endParser(); owner._handle.endParser();
@ -131,14 +142,14 @@ function loadSNI(info) {
let once = false; let once = false;
owner._SNICallback(servername, (err, context) => { owner._SNICallback(servername, (err, context) => {
if (once) if (once)
return owner.destroy(new errors.Error('ERR_MULTIPLE_CALLBACK')); return owner.destroy(new ERR_MULTIPLE_CALLBACK());
once = true; once = true;
if (err) if (err)
return owner.destroy(err); return owner.destroy(err);
if (owner._handle === null) 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` // TODO(indutny): eventually disallow raw `SecureContext`
if (context) if (context)
@ -175,14 +186,14 @@ function requestOCSP(socket, info) {
let once = false; let once = false;
const onOCSP = (err, response) => { const onOCSP = (err, response) => {
if (once) if (once)
return socket.destroy(new errors.Error('ERR_MULTIPLE_CALLBACK')); return socket.destroy(new ERR_MULTIPLE_CALLBACK());
once = true; once = true;
if (err) if (err)
return socket.destroy(err); return socket.destroy(err);
if (socket._handle === null) if (socket._handle === null)
return socket.destroy(new errors.Error('ERR_SOCKET_CLOSED')); return socket.destroy(new ERR_SOCKET_CLOSED());
if (response) if (response)
socket._handle.setOCSPResponse(response); socket._handle.setOCSPResponse(response);
@ -217,7 +228,7 @@ function onnewsession(key, session) {
once = true; once = true;
if (owner._handle === null) if (owner._handle === null)
return owner.destroy(new errors.Error('ERR_SOCKET_CLOSED')); return owner.destroy(new ERR_SOCKET_CLOSED());
this.newSessionDone(); this.newSessionDone();
@ -570,7 +581,7 @@ TLSSocket.prototype.renegotiate = function(options, callback) {
} }
if (!this._handle.renegotiate()) { if (!this._handle.renegotiate()) {
if (callback) { if (callback) {
process.nextTick(callback, new errors.Error('ERR_TLS_RENEGOTIATE')); process.nextTick(callback, new ERR_TLS_RENEGOTIATE());
} }
return false; return false;
} }
@ -594,7 +605,7 @@ TLSSocket.prototype.getTLSTicket = function getTLSTicket() {
}; };
TLSSocket.prototype._handleTimeout = function() { 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) { TLSSocket.prototype._emitTLSError = function(err) {
@ -656,11 +667,11 @@ TLSSocket.prototype._start = function() {
TLSSocket.prototype.setServername = function(name) { TLSSocket.prototype.setServername = function(name) {
if (typeof name !== 'string') { 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) { if (this._tlsOptions.isServer) {
throw new errors.Error('ERR_TLS_SNI_FROM_SERVER'); throw new ERR_TLS_SNI_FROM_SERVER();
} }
this._handle.setServername(name); this._handle.setServername(name);
@ -855,7 +866,7 @@ function Server(options, listener) {
} else if (options == null || typeof options === 'object') { } else if (options == null || typeof options === 'object') {
options = options || {}; options = options || {};
} else { } 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; this[kSNICallback] = options.SNICallback;
if (typeof this[kHandshakeTimeout] !== 'number') { 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) { if (this.sessionTimeout) {
@ -975,7 +986,7 @@ Server.prototype.setOptions = function(options) {
// SNI Contexts High-Level API // SNI Contexts High-Level API
Server.prototype.addContext = function(servername, context) { Server.prototype.addContext = function(servername, context) {
if (!servername) { if (!servername) {
throw new errors.Error('ERR_TLS_REQUIRED_SERVER_NAME'); throw new ERR_TLS_REQUIRED_SERVER_NAME();
} }
var re = new RegExp('^' + var re = new RegExp('^' +
@ -1040,7 +1051,7 @@ function onConnectSecure() {
// specified in options. // specified in options.
const ekeyinfo = this.getEphemeralKeyInfo(); const ekeyinfo = this.getEphemeralKeyInfo();
if (ekeyinfo.type === 'DH' && ekeyinfo.size < options.minDHSize) { 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.emit('error', err);
this.destroy(); this.destroy();
return; return;

View File

@ -12,7 +12,12 @@ const {
} = process.binding('constants').fs; } = process.binding('constants').fs;
const binding = process.binding('fs'); const binding = process.binding('fs');
const { Buffer, kMaxLength } = require('buffer'); 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 { getPathFromURL } = require('internal/url');
const { isUint8Array } = require('internal/util/types'); const { isUint8Array } = require('internal/util/types');
const { const {
@ -107,8 +112,7 @@ class FileHandle {
function validateFileHandle(handle) { function validateFileHandle(handle) {
if (!(handle instanceof FileHandle)) if (!(handle instanceof FileHandle))
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('filehandle', 'FileHandle');
'filehandle', 'FileHandle');
} }
async function writeFileHandle(filehandle, data, options) { async function writeFileHandle(filehandle, data, options) {
@ -139,7 +143,7 @@ async function readFileHandle(filehandle, options) {
return Buffer.alloc(0); return Buffer.alloc(0);
if (size > kMaxLength) if (size > kMaxLength)
throw new errors.RangeError('ERR_BUFFER_TOO_LARGE'); throw new ERR_BUFFER_TOO_LARGE();
const chunks = []; const chunks = [];
const chunkSize = Math.min(size, 16384); const chunkSize = Math.min(size, 16384);
@ -361,7 +365,7 @@ async function fchmod(handle, mode) {
validateFileHandle(handle); validateFileHandle(handle);
validateUint32(mode, 'mode'); validateUint32(mode, 'mode');
if (mode < 0 || mode > 0o777) 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); return binding.fchmod(handle.fd, mode, kUsePromises);
} }
@ -379,7 +383,7 @@ async function lchmod(path, mode) {
O_WRONLY | O_SYMLINK); O_WRONLY | O_SYMLINK);
return fchmod(fd, mode).finally(fd.close.bind(fd)); 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) { async function lchown(path, uid, gid) {
@ -388,7 +392,7 @@ async function lchown(path, uid, gid) {
O_WRONLY | O_SYMLINK); O_WRONLY | O_SYMLINK);
return fchmod(fd, uid, gid).finally(fd.close.bind(fd)); 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) { async function fchown(handle, uid, gid) {
@ -433,10 +437,7 @@ async function realpath(path, options) {
async function mkdtemp(prefix, options) { async function mkdtemp(prefix, options) {
options = getOptions(options, {}); options = getOptions(options, {});
if (!prefix || typeof prefix !== 'string') { if (!prefix || typeof prefix !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('prefix', 'string', prefix);
'prefix',
'string',
prefix);
} }
nullCheck(prefix); nullCheck(prefix);
return binding.mkdtemp(`${prefix}XXXXXX`, options.encoding, kUsePromises); return binding.mkdtemp(`${prefix}XXXXXX`, options.encoding, kUsePromises);

View File

@ -1,6 +1,9 @@
'use strict'; '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'); const async_wrap = process.binding('async_wrap');
/* async_hook_fields is a Uint32Array wrapping the uint32_t array of /* async_hook_fields is a Uint32Array wrapping the uint32_t array of
* Environment::AsyncHooks::fields_[]. Each index tracks the number of active * 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 (async_hook_fields[kCheck] <= 0) return;
if (!Number.isSafeInteger(asyncId) || asyncId < -1) { 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'); validateAsyncId(triggerAsyncId, 'triggerAsyncId');
if (async_hook_fields[kCheck] > 0 && if (async_hook_fields[kCheck] > 0 &&
(typeof type !== 'string' || type.length <= 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 // Short circuit all checks for the common case. Which is that no hooks have

View File

@ -1,7 +1,11 @@
'use strict'; 'use strict';
const binding = process.binding('buffer'); 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; const { setupBufferJS } = binding;
// Remove from the binding so that function is only available as exported here. // 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) { function checkInt(value, min, max, buf, offset, byteLength) {
if (value > max || value < min) { if (value > max || value < min) {
throw new RangeError('ERR_OUT_OF_RANGE', throw new ERR_OUT_OF_RANGE('value', `>= ${min} and <= ${max}`, value);
'value', `>= ${min} and <= ${max}`, value);
} }
checkBounds(buf, offset, byteLength); checkBounds(buf, offset, byteLength);
} }
function checkNumberType(value, type) { function checkNumberType(value, type) {
if (typeof value !== 'number') { if (typeof value !== 'number') {
throw new TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE(type || 'offset', 'number', value);
type || 'offset', 'number', value);
} }
} }
function boundsError(value, length, type) { function boundsError(value, length, type) {
if (Math.floor(value) !== value) { if (Math.floor(value) !== value) {
checkNumberType(value, type); checkNumberType(value, type);
throw new RangeError('ERR_OUT_OF_RANGE', throw new ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value);
type || 'offset', 'an integer', value);
} }
if (length < 0) 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', throw new ERR_OUT_OF_RANGE(type || 'offset',
type || 'offset', `>= ${type ? 1 : 0} and <= ${length}`,
`>= ${type ? 1 : 0} and <= ${length}`, value);
value);
} }
// Read integers. // 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. // `checkInt()` can not be used here because it checks two entries.
checkNumberType(offset); checkNumberType(offset);
if (value > max || value < min) { if (value > max || value < min) {
throw new RangeError('ERR_OUT_OF_RANGE', throw new ERR_OUT_OF_RANGE('value', `>= ${min} and <= ${max}`, value);
'value',
`>= ${min} and <= ${max}`, value);
} }
if (buf[offset] === undefined) if (buf[offset] === undefined)
boundsError(offset, buf.length - 1); boundsError(offset, buf.length - 1);

View File

@ -1,6 +1,19 @@
'use strict'; '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 { StringDecoder } = require('string_decoder');
const EventEmitter = require('events'); const EventEmitter = require('events');
const net = require('net'); const net = require('net');
@ -29,7 +42,6 @@ const {
UV_ESRCH UV_ESRCH
} = process.binding('uv'); } = process.binding('uv');
const errnoException = errors.errnoException;
const { SocketListSend, SocketListReceive } = SocketList; const { SocketListSend, SocketListReceive } = SocketList;
const MAX_HANDLE_RETRANSMISSIONS = 3; const MAX_HANDLE_RETRANSMISSIONS = 3;
@ -263,8 +275,7 @@ ChildProcess.prototype.spawn = function(options) {
var i; var i;
if (options === null || typeof options !== 'object') { if (options === null || typeof options !== 'object') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object', throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
options);
} }
// If no `stdio` option was given - use default // If no `stdio` option was given - use default
@ -281,16 +292,16 @@ ChildProcess.prototype.spawn = function(options) {
if (options.envPairs === undefined) if (options.envPairs === undefined)
options.envPairs = []; options.envPairs = [];
else if (!Array.isArray(options.envPairs)) { else if (!Array.isArray(options.envPairs)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.envPairs', throw new ERR_INVALID_ARG_TYPE('options.envPairs',
'Array', options.envPairs); 'Array',
options.envPairs);
} }
options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd); options.envPairs.push('NODE_CHANNEL_FD=' + ipcFd);
} }
if (typeof options.file !== 'string') { if (typeof options.file !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.file', 'string', throw new ERR_INVALID_ARG_TYPE('options.file', 'string', options.file);
options.file);
} }
this.spawnfile = options.file; this.spawnfile = options.file;
@ -299,8 +310,7 @@ ChildProcess.prototype.spawn = function(options) {
else if (options.args === undefined) else if (options.args === undefined)
this.spawnargs = []; this.spawnargs = [];
else else
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options.args', 'Array', throw new ERR_INVALID_ARG_TYPE('options.args', 'Array', options.args);
options.args);
var err = this._handle.spawn(options); var err = this._handle.spawn(options);
@ -587,8 +597,7 @@ function setupChannel(target, channel) {
options = undefined; options = undefined;
} else if (options !== undefined && } else if (options !== undefined &&
(options === null || typeof options !== 'object')) { (options === null || typeof options !== 'object')) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'Object', throw new ERR_INVALID_ARG_TYPE('options', 'Object', options);
options);
} }
options = Object.assign({ swallowErrors: false }, options); options = Object.assign({ swallowErrors: false }, options);
@ -596,7 +605,7 @@ function setupChannel(target, channel) {
if (this.connected) { if (this.connected) {
return this._send(message, handle, options, callback); 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') { if (typeof callback === 'function') {
process.nextTick(callback, ex); process.nextTick(callback, ex);
} else { } else {
@ -609,7 +618,7 @@ function setupChannel(target, channel) {
assert(this.connected || this.channel); assert(this.connected || this.channel);
if (message === undefined) if (message === undefined)
throw new errors.TypeError('ERR_MISSING_ARGS', 'message'); throw new ERR_MISSING_ARGS('message');
// Support legacy function signature // Support legacy function signature
if (typeof options === 'boolean') { if (typeof options === 'boolean') {
@ -636,7 +645,7 @@ function setupChannel(target, channel) {
} else if (handle instanceof UDP) { } else if (handle instanceof UDP) {
message.type = 'dgram.Native'; message.type = 'dgram.Native';
} else { } 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. // Queue-up message and handle if we haven't received ACK yet.
@ -736,7 +745,7 @@ function setupChannel(target, channel) {
target.disconnect = function() { target.disconnect = function() {
if (!this.connected) { if (!this.connected) {
this.emit('error', new errors.Error('ERR_IPC_DISCONNECTED')); this.emit('error', new ERR_IPC_DISCONNECTED());
return; return;
} }
@ -818,11 +827,10 @@ function _validateStdio(stdio, sync) {
case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break; case 'pipe': stdio = ['pipe', 'pipe', 'pipe']; break;
case 'inherit': stdio = [0, 1, 2]; break; case 'inherit': stdio = [0, 1, 2]; break;
default: default:
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'stdio', stdio); throw new ERR_INVALID_OPT_VALUE('stdio', stdio);
} }
} else if (!Array.isArray(stdio)) { } else if (!Array.isArray(stdio)) {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('stdio', util.inspect(stdio));
'stdio', util.inspect(stdio));
} }
// At least 3 stdio will be created // At least 3 stdio will be created
@ -864,9 +872,9 @@ function _validateStdio(stdio, sync) {
// Cleanup previously created pipes // Cleanup previously created pipes
cleanup(); cleanup();
if (!sync) if (!sync)
throw new errors.Error('ERR_IPC_ONE_PIPE'); throw new ERR_IPC_ONE_PIPE();
else else
throw new errors.Error('ERR_IPC_SYNC_FORK'); throw new ERR_IPC_SYNC_FORK();
} }
ipc = new Pipe(PipeConstants.IPC); ipc = new Pipe(PipeConstants.IPC);
@ -901,14 +909,12 @@ function _validateStdio(stdio, sync) {
} else if (isUint8Array(stdio) || typeof stdio === 'string') { } else if (isUint8Array(stdio) || typeof stdio === 'string') {
if (!sync) { if (!sync) {
cleanup(); cleanup();
throw new errors.TypeError('ERR_INVALID_SYNC_FORK_INPUT', throw new ERR_INVALID_SYNC_FORK_INPUT(util.inspect(stdio));
util.inspect(stdio));
} }
} else { } else {
// Cleanup // Cleanup
cleanup(); cleanup();
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'stdio', throw new ERR_INVALID_OPT_VALUE('stdio', util.inspect(stdio));
util.inspect(stdio));
} }
return acc; return acc;

View File

@ -6,7 +6,7 @@ const {
certVerifySpkac certVerifySpkac
} = process.binding('crypto'); } = process.binding('crypto');
const errors = require('internal/errors'); const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes;
const { isArrayBufferView } = require('internal/util/types'); const { isArrayBufferView } = require('internal/util/types');
const { const {
@ -15,8 +15,10 @@ const {
function verifySpkac(spkac) { function verifySpkac(spkac) {
if (!isArrayBufferView(spkac)) { if (!isArrayBufferView(spkac)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'spkac', throw new ERR_INVALID_ARG_TYPE(
['Buffer', 'TypedArray', 'DataView']); 'spkac',
['Buffer', 'TypedArray', 'DataView']
);
} }
return certVerifySpkac(spkac); return certVerifySpkac(spkac);
} }
@ -24,8 +26,10 @@ function verifySpkac(spkac) {
function exportPublicKey(spkac, encoding) { function exportPublicKey(spkac, encoding) {
spkac = toBuf(spkac, encoding); spkac = toBuf(spkac, encoding);
if (!isArrayBufferView(spkac)) { if (!isArrayBufferView(spkac)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'spkac', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'spkac',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
return certExportPublicKey(spkac); return certExportPublicKey(spkac);
} }
@ -33,8 +37,10 @@ function exportPublicKey(spkac, encoding) {
function exportChallenge(spkac, encoding) { function exportChallenge(spkac, encoding) {
spkac = toBuf(spkac, encoding); spkac = toBuf(spkac, encoding);
if (!isArrayBufferView(spkac)) { if (!isArrayBufferView(spkac)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'spkac', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'spkac',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
return certExportChallenge(spkac); return certExportChallenge(spkac);
} }

View File

@ -5,7 +5,10 @@ const {
RSA_PKCS1_PADDING RSA_PKCS1_PADDING
} = process.binding('constants').crypto; } = process.binding('constants').crypto;
const errors = require('internal/errors'); const {
ERR_CRYPTO_INVALID_STATE,
ERR_INVALID_ARG_TYPE
} = require('internal/errors').codes;
const { const {
getDefaultEncoding, getDefaultEncoding,
@ -64,12 +67,14 @@ function Cipher(cipher, password, options) {
return new Cipher(cipher, password, options); return new Cipher(cipher, password, options);
if (typeof cipher !== 'string') 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); password = toBuf(password);
if (!isArrayBufferView(password)) { if (!isArrayBufferView(password)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'password', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'password',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
this._handle = new CipherBase(true); this._handle = new CipherBase(true);
@ -103,8 +108,10 @@ Cipher.prototype.update = function update(data, inputEncoding, outputEncoding) {
outputEncoding = outputEncoding || encoding; outputEncoding = outputEncoding || encoding;
if (typeof data !== 'string' && !isArrayBufferView(data)) { if (typeof data !== 'string' && !isArrayBufferView(data)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'data', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'data',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
const ret = this._handle.update(data, inputEncoding); const ret = this._handle.update(data, inputEncoding);
@ -133,38 +140,38 @@ Cipher.prototype.final = function final(outputEncoding) {
Cipher.prototype.setAutoPadding = function setAutoPadding(ap) { Cipher.prototype.setAutoPadding = function setAutoPadding(ap) {
if (this._handle.setAutoPadding(ap) === false) if (this._handle.setAutoPadding(ap) === false)
throw new errors.Error('ERR_CRYPTO_INVALID_STATE', 'setAutoPadding'); throw new ERR_CRYPTO_INVALID_STATE('setAutoPadding');
return this; return this;
}; };
Cipher.prototype.getAuthTag = function getAuthTag() { Cipher.prototype.getAuthTag = function getAuthTag() {
const ret = this._handle.getAuthTag(); const ret = this._handle.getAuthTag();
if (ret === undefined) if (ret === undefined)
throw new errors.Error('ERR_CRYPTO_INVALID_STATE', 'getAuthTag'); throw new ERR_CRYPTO_INVALID_STATE('getAuthTag');
return ret; return ret;
}; };
Cipher.prototype.setAuthTag = function setAuthTag(tagbuf) { Cipher.prototype.setAuthTag = function setAuthTag(tagbuf) {
if (!isArrayBufferView(tagbuf)) { if (!isArrayBufferView(tagbuf)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'buffer', throw new ERR_INVALID_ARG_TYPE('buffer',
['Buffer', 'TypedArray', 'DataView']); ['Buffer', 'TypedArray', 'DataView']);
} }
// Do not do a normal falsy check because the method returns // Do not do a normal falsy check because the method returns
// undefined if it succeeds. Returns false specifically if it // undefined if it succeeds. Returns false specifically if it
// errored // errored
if (this._handle.setAuthTag(tagbuf) === false) if (this._handle.setAuthTag(tagbuf) === false)
throw new errors.Error('ERR_CRYPTO_INVALID_STATE', 'setAuthTag'); throw new ERR_CRYPTO_INVALID_STATE('setAuthTag');
return this; return this;
}; };
Cipher.prototype.setAAD = function setAAD(aadbuf) { Cipher.prototype.setAAD = function setAAD(aadbuf) {
if (!isArrayBufferView(aadbuf)) { if (!isArrayBufferView(aadbuf)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'buffer', throw new ERR_INVALID_ARG_TYPE('buffer',
['Buffer', 'TypedArray', 'DataView']); ['Buffer', 'TypedArray', 'DataView']);
} }
if (this._handle.setAAD(aadbuf) === false) if (this._handle.setAAD(aadbuf) === false)
throw new errors.Error('ERR_CRYPTO_INVALID_STATE', 'setAAD'); throw new ERR_CRYPTO_INVALID_STATE('setAAD');
return this; return this;
}; };
@ -173,18 +180,22 @@ function Cipheriv(cipher, key, iv, options) {
return new Cipheriv(cipher, key, iv, options); return new Cipheriv(cipher, key, iv, options);
if (typeof cipher !== 'string') 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); key = toBuf(key);
if (!isArrayBufferView(key)) { if (!isArrayBufferView(key)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'key',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
iv = toBuf(iv); iv = toBuf(iv);
if (iv !== null && !isArrayBufferView(iv)) { if (iv !== null && !isArrayBufferView(iv)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'iv', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'iv',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
this._handle = new CipherBase(true); this._handle = new CipherBase(true);
@ -211,12 +222,14 @@ function Decipher(cipher, password, options) {
return new Decipher(cipher, password, options); return new Decipher(cipher, password, options);
if (typeof cipher !== 'string') 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); password = toBuf(password);
if (!isArrayBufferView(password)) { if (!isArrayBufferView(password)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'password', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'password',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
this._handle = new CipherBase(false); this._handle = new CipherBase(false);
@ -244,18 +257,22 @@ function Decipheriv(cipher, key, iv, options) {
return new Decipheriv(cipher, key, iv, options); return new Decipheriv(cipher, key, iv, options);
if (typeof cipher !== 'string') 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); key = toBuf(key);
if (!isArrayBufferView(key)) { if (!isArrayBufferView(key)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'key',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
iv = toBuf(iv); iv = toBuf(iv);
if (iv !== null && !isArrayBufferView(iv)) { if (iv !== null && !isArrayBufferView(iv)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'iv', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'iv',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
this._handle = new CipherBase(false); this._handle = new CipherBase(false);

View File

@ -1,7 +1,11 @@
'use strict'; 'use strict';
const { Buffer } = require('buffer'); 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 { isArrayBufferView } = require('internal/util/types');
const { const {
getDefaultEncoding, getDefaultEncoding,
@ -27,9 +31,10 @@ function DiffieHellman(sizeOrKey, keyEncoding, generator, genEncoding) {
if (typeof sizeOrKey !== 'number' && if (typeof sizeOrKey !== 'number' &&
typeof sizeOrKey !== 'string' && typeof sizeOrKey !== 'string' &&
!isArrayBufferView(sizeOrKey)) { !isArrayBufferView(sizeOrKey)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'sizeOrKey', throw new ERR_INVALID_ARG_TYPE(
['number', 'string', 'Buffer', 'TypedArray', 'sizeOrKey',
'DataView']); ['number', 'string', 'Buffer', 'TypedArray', 'DataView']
);
} }
if (keyEncoding) { if (keyEncoding) {
@ -97,7 +102,7 @@ function dhComputeSecret(key, inEnc, outEnc) {
outEnc = outEnc || encoding; outEnc = outEnc || encoding;
var ret = this._handle.computeSecret(toBuf(key, inEnc)); var ret = this._handle.computeSecret(toBuf(key, inEnc));
if (typeof ret === 'string') 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') if (outEnc && outEnc !== 'buffer')
ret = ret.toString(outEnc); ret = ret.toString(outEnc);
return ret; return ret;
@ -175,7 +180,7 @@ function ECDH(curve) {
return new ECDH(curve); return new ECDH(curve);
if (typeof curve !== 'string') 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); this._handle = new _ECDH(curve);
} }
@ -202,7 +207,7 @@ ECDH.prototype.getPublicKey = function getPublicKey(encoding, format) {
else if (format === 'uncompressed') else if (format === 'uncompressed')
f = POINT_CONVERSION_UNCOMPRESSED; f = POINT_CONVERSION_UNCOMPRESSED;
else else
throw new errors.TypeError('ERR_CRYPTO_ECDH_INVALID_FORMAT', format); throw new ERR_CRYPTO_ECDH_INVALID_FORMAT(format);
} else { } else {
f = POINT_CONVERSION_UNCOMPRESSED; f = POINT_CONVERSION_UNCOMPRESSED;
} }

View File

@ -12,7 +12,12 @@ const {
const { Buffer } = require('buffer'); 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 { inherits } = require('util');
const { normalizeEncoding } = require('internal/util'); const { normalizeEncoding } = require('internal/util');
const { isArrayBufferView } = require('internal/util/types'); const { isArrayBufferView } = require('internal/util/types');
@ -24,7 +29,7 @@ function Hash(algorithm, options) {
if (!(this instanceof Hash)) if (!(this instanceof Hash))
return new Hash(algorithm, options); return new Hash(algorithm, options);
if (typeof algorithm !== 'string') 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._handle = new _Hash(algorithm);
this[kState] = { this[kState] = {
[kFinalized]: false [kFinalized]: false
@ -47,15 +52,15 @@ Hash.prototype._flush = function _flush(callback) {
Hash.prototype.update = function update(data, encoding) { Hash.prototype.update = function update(data, encoding) {
const state = this[kState]; const state = this[kState];
if (state[kFinalized]) if (state[kFinalized])
throw new errors.Error('ERR_CRYPTO_HASH_FINALIZED'); throw new ERR_CRYPTO_HASH_FINALIZED();
if (typeof data !== 'string' && !isArrayBufferView(data)) { if (typeof data !== 'string' && !isArrayBufferView(data)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'data', throw new ERR_INVALID_ARG_TYPE('data',
['string', 'TypedArray', 'DataView']); ['string', 'TypedArray', 'DataView']);
} }
if (!this._handle.update(data, encoding || getDefaultEncoding())) 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; return this;
}; };
@ -63,10 +68,10 @@ Hash.prototype.update = function update(data, encoding) {
Hash.prototype.digest = function digest(outputEncoding) { Hash.prototype.digest = function digest(outputEncoding) {
const state = this[kState]; const state = this[kState];
if (state[kFinalized]) if (state[kFinalized])
throw new errors.Error('ERR_CRYPTO_HASH_FINALIZED'); throw new ERR_CRYPTO_HASH_FINALIZED();
outputEncoding = outputEncoding || getDefaultEncoding(); outputEncoding = outputEncoding || getDefaultEncoding();
if (normalizeEncoding(outputEncoding) === 'utf16le') 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. // Explicit conversion for backward compatibility.
const ret = this._handle.digest(`${outputEncoding}`); const ret = this._handle.digest(`${outputEncoding}`);
@ -79,10 +84,9 @@ function Hmac(hmac, key, options) {
if (!(this instanceof Hmac)) if (!(this instanceof Hmac))
return new Hmac(hmac, key, options); return new Hmac(hmac, key, options);
if (typeof hmac !== 'string') 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)) { if (typeof key !== 'string' && !isArrayBufferView(key)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key', throw new ERR_INVALID_ARG_TYPE('key', ['string', 'TypedArray', 'DataView']);
['string', 'TypedArray', 'DataView']);
} }
this._handle = new _Hmac(); this._handle = new _Hmac();
this._handle.init(hmac, toBuf(key)); this._handle.init(hmac, toBuf(key));
@ -100,7 +104,7 @@ Hmac.prototype.digest = function digest(outputEncoding) {
const state = this[kState]; const state = this[kState];
outputEncoding = outputEncoding || getDefaultEncoding(); outputEncoding = outputEncoding || getDefaultEncoding();
if (normalizeEncoding(outputEncoding) === 'utf16le') 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]) { if (state[kFinalized]) {
const buf = Buffer.from(''); const buf = Buffer.from('');

View File

@ -1,6 +1,11 @@
'use strict'; '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 { const {
getDefaultEncoding, getDefaultEncoding,
toBuf toBuf
@ -20,7 +25,7 @@ function pbkdf2(password, salt, iterations, keylen, digest, callback) {
} }
if (typeof callback !== 'function') if (typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
return _pbkdf2(password, salt, iterations, keylen, digest, 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) { function _pbkdf2(password, salt, iterations, keylen, digest, callback) {
if (digest !== null && typeof digest !== 'string') if (digest !== null && typeof digest !== 'string')
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'digest', throw new ERR_INVALID_ARG_TYPE('digest', ['string', 'null']);
['string', 'null']);
password = toBuf(password); password = toBuf(password);
salt = toBuf(salt); salt = toBuf(salt);
if (!isArrayBufferView(password)) { if (!isArrayBufferView(password)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'password', throw new ERR_INVALID_ARG_TYPE('password',
['string', 'Buffer', 'TypedArray']); ['string', 'Buffer', 'TypedArray']);
} }
if (!isArrayBufferView(salt)) { if (!isArrayBufferView(salt)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'salt', throw new ERR_INVALID_ARG_TYPE('salt', ['string', 'Buffer', 'TypedArray']);
['string', 'Buffer', 'TypedArray']);
} }
if (typeof iterations !== 'number') 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) if (iterations < 0)
throw new errors.RangeError('ERR_OUT_OF_RANGE', throw new ERR_OUT_OF_RANGE('iterations',
'iterations', 'a non-negative number',
'a non-negative number', iterations);
iterations);
if (typeof keylen !== 'number') 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 || if (keylen < 0 ||
!Number.isFinite(keylen) || !Number.isFinite(keylen) ||
keylen > INT_MAX) { keylen > INT_MAX) {
throw new errors.RangeError('ERR_OUT_OF_RANGE', 'keylen'); throw new ERR_OUT_OF_RANGE('keylen');
} }
const encoding = getDefaultEncoding(); const encoding = getDefaultEncoding();
@ -71,7 +73,7 @@ function _pbkdf2(password, salt, iterations, keylen, digest, callback) {
if (encoding === 'buffer') { if (encoding === 'buffer') {
const ret = PBKDF2(password, salt, iterations, keylen, digest, callback); const ret = PBKDF2(password, salt, iterations, keylen, digest, callback);
if (ret === -1) if (ret === -1)
throw new errors.TypeError('ERR_CRYPTO_INVALID_DIGEST', digest); throw new ERR_CRYPTO_INVALID_DIGEST(digest);
return ret; return ret;
} }
@ -83,11 +85,11 @@ function _pbkdf2(password, salt, iterations, keylen, digest, callback) {
callback(er, ret); callback(er, ret);
} }
if (PBKDF2(password, salt, iterations, keylen, digest, next) === -1) 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 { } else {
const ret = PBKDF2(password, salt, iterations, keylen, digest); const ret = PBKDF2(password, salt, iterations, keylen, digest);
if (ret === -1) if (ret === -1)
throw new errors.TypeError('ERR_CRYPTO_INVALID_DIGEST', digest); throw new ERR_CRYPTO_INVALID_DIGEST(digest);
return ret.toString(encoding); return ret.toString(encoding);
} }
} }

View File

@ -1,6 +1,10 @@
'use strict'; '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 { isArrayBufferView } = require('internal/util/types');
const { const {
randomBytes: _randomBytes, randomBytes: _randomBytes,
@ -12,43 +16,42 @@ const kMaxUint32 = Math.pow(2, 32) - 1;
function assertOffset(offset, length) { function assertOffset(offset, length) {
if (typeof offset !== 'number' || Number.isNaN(offset)) { 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) { 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) { 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) { function assertSize(size, offset = 0, length = Infinity) {
if (typeof size !== 'number' || Number.isNaN(size)) { 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) { 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) { 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) { function randomBytes(size, cb) {
assertSize(size); assertSize(size);
if (cb !== undefined && typeof cb !== 'function') if (cb !== undefined && typeof cb !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
return _randomBytes(size, cb); return _randomBytes(size, cb);
} }
function randomFillSync(buf, offset = 0, size) { function randomFillSync(buf, offset = 0, size) {
if (!isArrayBufferView(buf)) { if (!isArrayBufferView(buf)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('buf', 'ArrayBufferView');
'buf', 'ArrayBufferView');
} }
const elementSize = buf.BYTES_PER_ELEMENT || 1; const elementSize = buf.BYTES_PER_ELEMENT || 1;
@ -69,8 +72,7 @@ function randomFillSync(buf, offset = 0, size) {
function randomFill(buf, offset, size, cb) { function randomFill(buf, offset, size, cb) {
if (!isArrayBufferView(buf)) { if (!isArrayBufferView(buf)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('buf', 'ArrayBufferView');
'buf', 'ArrayBufferView');
} }
const elementSize = buf.BYTES_PER_ELEMENT || 1; const elementSize = buf.BYTES_PER_ELEMENT || 1;
@ -84,7 +86,7 @@ function randomFill(buf, offset, size, cb) {
offset *= elementSize; offset *= elementSize;
size = buf.byteLength - offset; size = buf.byteLength - offset;
} else if (typeof cb !== 'function') { } else if (typeof cb !== 'function') {
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
} }
if (size === undefined) { if (size === undefined) {
size = buf.byteLength - offset; size = buf.byteLength - offset;

View File

@ -1,6 +1,10 @@
'use strict'; '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 { const {
Sign: _Sign, Sign: _Sign,
Verify: _Verify Verify: _Verify
@ -21,7 +25,7 @@ function Sign(algorithm, options) {
if (!(this instanceof Sign)) if (!(this instanceof Sign))
return new Sign(algorithm, options); return new Sign(algorithm, options);
if (typeof algorithm !== 'string') 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 = new _Sign();
this._handle.init(algorithm); this._handle.init(algorithm);
@ -39,8 +43,10 @@ Sign.prototype.update = function update(data, encoding) {
encoding = encoding || getDefaultEncoding(); encoding = encoding || getDefaultEncoding();
data = toBuf(data, encoding); data = toBuf(data, encoding);
if (!isArrayBufferView(data)) { if (!isArrayBufferView(data)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'data', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'data',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
this._handle.update(data); this._handle.update(data);
return this; return this;
@ -48,7 +54,7 @@ Sign.prototype.update = function update(data, encoding) {
Sign.prototype.sign = function sign(options, encoding) { Sign.prototype.sign = function sign(options, encoding) {
if (!options) if (!options)
throw new errors.Error('ERR_CRYPTO_SIGN_KEY_REQUIRED'); throw new ERR_CRYPTO_SIGN_KEY_REQUIRED();
var key = options.key || options; var key = options.key || options;
var passphrase = options.passphrase || null; var passphrase = options.passphrase || null;
@ -59,9 +65,7 @@ Sign.prototype.sign = function sign(options, encoding) {
if (options.padding === options.padding >> 0) { if (options.padding === options.padding >> 0) {
rsaPadding = options.padding; rsaPadding = options.padding;
} else { } else {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('padding', options.padding);
'padding',
options.padding);
} }
} }
@ -70,16 +74,16 @@ Sign.prototype.sign = function sign(options, encoding) {
if (options.saltLength === options.saltLength >> 0) { if (options.saltLength === options.saltLength >> 0) {
pssSaltLength = options.saltLength; pssSaltLength = options.saltLength;
} else { } else {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('saltLength', options.saltLength);
'saltLength',
options.saltLength);
} }
} }
key = toBuf(key); key = toBuf(key);
if (!isArrayBufferView(key)) { if (!isArrayBufferView(key)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'key',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
var ret = this._handle.sign(key, passphrase, rsaPadding, pssSaltLength); var ret = this._handle.sign(key, passphrase, rsaPadding, pssSaltLength);
@ -96,7 +100,7 @@ function Verify(algorithm, options) {
if (!(this instanceof Verify)) if (!(this instanceof Verify))
return new Verify(algorithm, options); return new Verify(algorithm, options);
if (typeof algorithm !== 'string') 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 = new _Verify();
this._handle.init(algorithm); this._handle.init(algorithm);
@ -118,9 +122,7 @@ Verify.prototype.verify = function verify(options, signature, sigEncoding) {
if (options.padding === options.padding >> 0) { if (options.padding === options.padding >> 0) {
rsaPadding = options.padding; rsaPadding = options.padding;
} else { } else {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('padding', options.padding);
'padding',
options.padding);
} }
} }
@ -129,22 +131,24 @@ Verify.prototype.verify = function verify(options, signature, sigEncoding) {
if (options.saltLength === options.saltLength >> 0) { if (options.saltLength === options.saltLength >> 0) {
pssSaltLength = options.saltLength; pssSaltLength = options.saltLength;
} else { } else {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('saltLength', options.saltLength);
'saltLength',
options.saltLength);
} }
} }
key = toBuf(key); key = toBuf(key);
if (!isArrayBufferView(key)) { if (!isArrayBufferView(key)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'key', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'key',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
signature = toBuf(signature, sigEncoding); signature = toBuf(signature, sigEncoding);
if (!isArrayBufferView(signature)) { if (!isArrayBufferView(signature)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'signature', throw new ERR_INVALID_ARG_TYPE(
['string', 'Buffer', 'TypedArray', 'DataView']); 'signature',
['string', 'Buffer', 'TypedArray', 'DataView']
);
} }
return this._handle.verify(key, signature, rsaPadding, pssSaltLength); return this._handle.verify(key, signature, rsaPadding, pssSaltLength);

View File

@ -12,7 +12,11 @@ const {
ENGINE_METHOD_ALL ENGINE_METHOD_ALL
} = process.binding('constants').crypto; } = 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 { Buffer } = require('buffer');
const { const {
cachedResult, cachedResult,
@ -50,10 +54,10 @@ const getCurves = cachedResult(() => filterDuplicateStrings(_getCurves()));
function setEngine(id, flags) { function setEngine(id, flags) {
if (typeof id !== 'string') 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') 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; flags = flags >>> 0;
// Use provided engine for everything by default // Use provided engine for everything by default
@ -61,20 +65,18 @@ function setEngine(id, flags) {
flags = ENGINE_METHOD_ALL; flags = ENGINE_METHOD_ALL;
if (!_setEngine(id, flags)) if (!_setEngine(id, flags))
throw new errors.Error('ERR_CRYPTO_ENGINE_UNKNOWN', id); throw new ERR_CRYPTO_ENGINE_UNKNOWN(id);
} }
function timingSafeEqual(a, b) { function timingSafeEqual(a, b) {
if (!isArrayBufferView(a)) { if (!isArrayBufferView(a)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'a', throw new ERR_INVALID_ARG_TYPE('a', ['Buffer', 'TypedArray', 'DataView']);
['Buffer', 'TypedArray', 'DataView']);
} }
if (!isArrayBufferView(b)) { if (!isArrayBufferView(b)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'b', throw new ERR_INVALID_ARG_TYPE('b', ['Buffer', 'TypedArray', 'DataView']);
['Buffer', 'TypedArray', 'DataView']);
} }
if (a.length !== b.length) { 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); return _timingSafeEqual(a, b);
} }

View File

@ -3,7 +3,13 @@
// An implementation of the WHATWG Encoding Standard // An implementation of the WHATWG Encoding Standard
// https://encoding.spec.whatwg.org // 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 kHandle = Symbol('handle');
const kFlags = Symbol('flags'); const kFlags = Symbol('flags');
const kEncoding = Symbol('encoding'); const kEncoding = Symbol('encoding');
@ -35,17 +41,17 @@ function lazyBuffer() {
function validateEncoder(obj) { function validateEncoder(obj) {
if (obj == null || obj[kEncoder] !== true) if (obj == null || obj[kEncoder] !== true)
throw new errors.TypeError('ERR_INVALID_THIS', 'TextEncoder'); throw new ERR_INVALID_THIS('TextEncoder');
} }
function validateDecoder(obj) { function validateDecoder(obj) {
if (obj == null || obj[kDecoder] !== true) 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) { function validateArgument(prop, expected, propName, expectedName) {
if (typeof prop !== expected) 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; const CONVERTER_FLAGS_FLUSH = 0x1;
@ -360,7 +366,7 @@ function makeTextDecoderICU() {
const enc = getEncodingFromLabel(encoding); const enc = getEncodingFromLabel(encoding);
if (enc === undefined) if (enc === undefined)
throw new errors.RangeError('ERR_ENCODING_NOT_SUPPORTED', encoding); throw new ERR_ENCODING_NOT_SUPPORTED(encoding);
var flags = 0; var flags = 0;
if (options !== null) { if (options !== null) {
@ -370,7 +376,7 @@ function makeTextDecoderICU() {
const handle = getConverter(enc, flags); const handle = getConverter(enc, flags);
if (handle === undefined) if (handle === undefined)
throw new errors.Error('ERR_ENCODING_NOT_SUPPORTED', encoding); throw new ERR_ENCODING_NOT_SUPPORTED(encoding);
this[kDecoder] = true; this[kDecoder] = true;
this[kHandle] = handle; this[kHandle] = handle;
@ -384,8 +390,8 @@ function makeTextDecoderICU() {
if (isArrayBuffer(input)) { if (isArrayBuffer(input)) {
input = lazyBuffer().from(input); input = lazyBuffer().from(input);
} else if (!isArrayBufferView(input)) { } else if (!isArrayBufferView(input)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'input', throw new ERR_INVALID_ARG_TYPE('input',
['ArrayBuffer', 'ArrayBufferView']); ['ArrayBuffer', 'ArrayBufferView']);
} }
validateArgument(options, 'object', 'options', 'Object'); validateArgument(options, 'object', 'options', 'Object');
@ -395,8 +401,7 @@ function makeTextDecoderICU() {
const ret = _decode(this[kHandle], input, flags); const ret = _decode(this[kHandle], input, flags);
if (typeof ret === 'number') { if (typeof ret === 'number') {
const err = new errors.TypeError('ERR_ENCODING_INVALID_ENCODED_DATA', const err = new ERR_ENCODING_INVALID_ENCODED_DATA(this.encoding);
this.encoding);
err.errno = ret; err.errno = ret;
throw err; throw err;
} }
@ -428,12 +433,12 @@ function makeTextDecoderJS() {
const enc = getEncodingFromLabel(encoding); const enc = getEncodingFromLabel(encoding);
if (enc === undefined || !hasConverter(enc)) if (enc === undefined || !hasConverter(enc))
throw new errors.RangeError('ERR_ENCODING_NOT_SUPPORTED', encoding); throw new ERR_ENCODING_NOT_SUPPORTED(encoding);
var flags = 0; var flags = 0;
if (options !== null) { if (options !== null) {
if (options.fatal) { 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; flags |= options.ignoreBOM ? CONVERTER_FLAGS_IGNORE_BOM : 0;
} }
@ -454,8 +459,8 @@ function makeTextDecoderJS() {
input = lazyBuffer().from(input.buffer, input.byteOffset, input = lazyBuffer().from(input.buffer, input.byteOffset,
input.byteLength); input.byteLength);
} else { } else {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'input', throw new ERR_INVALID_ARG_TYPE('input',
['ArrayBuffer', 'ArrayBufferView']); ['ArrayBuffer', 'ArrayBufferView']);
} }
validateArgument(options, 'object', 'options', 'Object'); validateArgument(options, 'object', 'options', 'Object');

View File

@ -320,7 +320,7 @@ function createErrDiff(actual, expected, operator) {
class AssertionError extends Error { class AssertionError extends Error {
constructor(options) { constructor(options) {
if (typeof options !== 'object' || options === null) { 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 { var {
actual, actual,
@ -600,7 +600,7 @@ module.exports = exports = {
// Note: Node.js specific errors must begin with the prefix ERR_ // Note: Node.js specific errors must begin with the prefix ERR_
E('ERR_ARG_NOT_ITERABLE', '%s must be iterable', TypeError); 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_CALLBACK', '%s must be a function', TypeError);
E('ERR_ASYNC_TYPE', 'Invalid name for async "type": %s', TypeError); E('ERR_ASYNC_TYPE', 'Invalid name for async "type": %s', TypeError);
E('ERR_BUFFER_OUT_OF_BOUNDS', bufferOutOfBounds, RangeError); 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); 'Custom engines not supported by this OpenSSL', Error);
E('ERR_CRYPTO_ECDH_INVALID_FORMAT', 'Invalid ECDH format: %s', TypeError); E('ERR_CRYPTO_ECDH_INVALID_FORMAT', 'Invalid ECDH format: %s', TypeError);
E('ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY', 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_ENGINE_UNKNOWN', 'Engine "%s" was not found', Error);
E('ERR_CRYPTO_FIPS_FORCED', E('ERR_CRYPTO_FIPS_FORCED',
'Cannot set FIPS mode, it was forced with --force-fips at startup.', Error); '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', E('ERR_ENCODING_INVALID_ENCODED_DATA',
'The encoded data was not valid for encoding %s', TypeError); 'The encoded data was not valid for encoding %s', TypeError);
E('ERR_ENCODING_NOT_SUPPORTED', 'The "%s" encoding is not supported', 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_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value', Error);
E('ERR_FS_INVALID_SYMLINK_TYPE', E('ERR_FS_INVALID_SYMLINK_TYPE',
'Symlink type must be one of "dir", "file", or "junction". Received "%s"', '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_STDERR_CLOSE', 'process.stderr cannot be closed', Error);
E('ERR_STDOUT_CLOSE', 'process.stdout 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_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_NULL_VALUES', 'May not write null values to stream', TypeError);
E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error); E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error);
E('ERR_STREAM_READ_NOT_IMPLEMENTED', '_read() is not implemented', Error); E('ERR_STREAM_READ_NOT_IMPLEMENTED', '_read() is not implemented', Error);

View File

@ -2,7 +2,14 @@
const { Buffer, kMaxLength } = require('buffer'); const { Buffer, kMaxLength } = require('buffer');
const { Writable } = require('stream'); 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 { isUint8Array } = require('internal/util/types');
const fs = require('fs'); const fs = require('fs');
const pathModule = require('path'); const pathModule = require('path');
@ -34,7 +41,7 @@ const isWindows = process.platform === 'win32';
function assertEncoding(encoding) { function assertEncoding(encoding) {
if (encoding && !Buffer.isEncoding(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; defaultOptions.encoding = options;
options = defaultOptions; options = defaultOptions;
} else if (typeof options !== 'object') { } else if (typeof options !== 'object') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('options', ['string', 'Object'], options);
'options',
['string', 'Object'],
options);
} }
if (options.encoding !== 'buffer') if (options.encoding !== 'buffer')
@ -97,9 +101,11 @@ function nullCheck(path, propName, throwError = true) {
return; return;
} }
const err = new errors.Error( const err = new ERR_INVALID_ARG_VALUE(
'ERR_INVALID_ARG_VALUE', propName, path, propName,
'must be a string or Uint8Array without null bytes'); path,
'must be a string or Uint8Array without null bytes'
);
if (throwError) { if (throwError) {
Error.captureStackTrace(err, nullCheck); Error.captureStackTrace(err, nullCheck);
@ -233,7 +239,7 @@ function stringToFlags(flags) {
case 'sa+': return O_APPEND | O_CREAT | O_RDWR | O_SYNC; 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) { function stringToSymlinkType(type) {
@ -249,7 +255,7 @@ function stringToSymlinkType(type) {
case 'file': case 'file':
break; break;
default: 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); Error.captureStackTrace(err, stringToSymlinkType);
throw err; throw err;
} }
@ -312,16 +318,12 @@ function toUnixTimestamp(time, name = 'time') {
// convert to 123.456 UNIX timestamp // convert to 123.456 UNIX timestamp
return time.getTime() / 1000; return time.getTime() / 1000;
} }
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE(name, ['Date', 'Time in seconds'], time);
name,
['Date', 'Time in seconds'],
time);
} }
function validateBuffer(buffer) { function validateBuffer(buffer) {
if (!isUint8Array(buffer)) { if (!isUint8Array(buffer)) {
const err = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'buffer', const err = new ERR_INVALID_ARG_TYPE('buffer', ['Buffer', 'Uint8Array']);
['Buffer', 'Uint8Array']);
Error.captureStackTrace(err, validateBuffer); Error.captureStackTrace(err, validateBuffer);
throw err; throw err;
} }
@ -331,7 +333,7 @@ function validateLen(len) {
let err; let err;
if (!isInt32(len)) if (!isInt32(len))
err = new errors.TypeError('ERR_INVALID_ARG_TYPE', 'len', 'integer'); err = new ERR_INVALID_ARG_TYPE('len', 'integer');
if (err !== undefined) { if (err !== undefined) {
Error.captureStackTrace(err, validateLen); Error.captureStackTrace(err, validateLen);
@ -343,9 +345,9 @@ function validateOffsetLengthRead(offset, length, bufferLength) {
let err; let err;
if (offset < 0 || offset >= bufferLength) { 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) { } 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) { if (err !== undefined) {
@ -358,9 +360,9 @@ function validateOffsetLengthWrite(offset, length, byteLength) {
let err; let err;
if (offset > byteLength) { 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) { } 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) { if (err !== undefined) {
@ -377,8 +379,7 @@ function validatePath(path, propName) {
} }
if (typeof path !== 'string' && !isUint8Array(path)) { if (typeof path !== 'string' && !isUint8Array(path)) {
err = new errors.TypeError('ERR_INVALID_ARG_TYPE', propName, err = new ERR_INVALID_ARG_TYPE(propName, ['string', 'Buffer', 'URL']);
['string', 'Buffer', 'URL']);
} else { } else {
err = nullCheck(path, propName, false); err = nullCheck(path, propName, false);
} }
@ -393,7 +394,7 @@ function validateUint32(value, propName) {
let err; let err;
if (!isUint32(value)) if (!isUint32(value))
err = new errors.TypeError('ERR_INVALID_ARG_TYPE', propName, 'integer'); err = new ERR_INVALID_ARG_TYPE(propName, 'integer');
if (err !== undefined) { if (err !== undefined) {
Error.captureStackTrace(err, validateUint32); Error.captureStackTrace(err, validateUint32);

View File

@ -4,7 +4,18 @@ const Stream = require('stream');
const Readable = Stream.Readable; const Readable = Stream.Readable;
const binding = process.binding('http2'); const binding = process.binding('http2');
const constants = binding.constants; 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 { kSocket } = require('internal/http2/util');
const kFinish = Symbol('finish'); const kFinish = Symbol('finish');
@ -42,11 +53,11 @@ let statusMessageWarned = false;
function assertValidHeader(name, value) { function assertValidHeader(name, value) {
let err; let err;
if (name === '' || typeof name !== 'string') { 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)) { } 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) { } 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) { if (err !== undefined) {
Error.captureStackTrace(err, assertValidHeader); Error.captureStackTrace(err, assertValidHeader);
@ -163,7 +174,7 @@ const proxySocketHandler = {
case 'read': case 'read':
case 'pause': case 'pause':
case 'resume': case 'resume':
throw new errors.Error('ERR_HTTP2_NO_SOCKET_MANIPULATION'); throw new ERR_HTTP2_NO_SOCKET_MANIPULATION();
default: default:
const ref = stream.session !== undefined ? const ref = stream.session !== undefined ?
stream.session[kSocket] : stream; stream.session[kSocket] : stream;
@ -199,7 +210,7 @@ const proxySocketHandler = {
case 'read': case 'read':
case 'pause': case 'pause':
case 'resume': case 'resume':
throw new errors.Error('ERR_HTTP2_NO_SOCKET_MANIPULATION'); throw new ERR_HTTP2_NO_SOCKET_MANIPULATION();
default: default:
const ref = stream.session !== undefined ? const ref = stream.session !== undefined ?
stream.session[kSocket] : stream; stream.session[kSocket] : stream;
@ -292,7 +303,7 @@ class Http2ServerRequest extends Readable {
state.didRead = true; state.didRead = true;
process.nextTick(resumeStream, this[kStream]); process.nextTick(resumeStream, this[kStream]);
} else { } 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) { set method(method) {
if (typeof method !== 'string' || method.trim() === '') 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; this[kHeaders][HTTP2_HEADER_METHOD] = method;
} }
@ -419,15 +430,15 @@ class Http2ServerResponse extends Stream {
set statusCode(code) { set statusCode(code) {
code |= 0; code |= 0;
if (code >= 100 && code < 200) 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) 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; this[kState].statusCode = code;
} }
setTrailer(name, value) { setTrailer(name, value) {
if (typeof name !== 'string') 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(); name = name.trim().toLowerCase();
assertValidHeader(name, value); assertValidHeader(name, value);
@ -445,7 +456,7 @@ class Http2ServerResponse extends Stream {
getHeader(name) { getHeader(name) {
if (typeof name !== 'string') 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(); name = name.trim().toLowerCase();
return this[kHeaders][name]; return this[kHeaders][name];
@ -461,7 +472,7 @@ class Http2ServerResponse extends Stream {
hasHeader(name) { hasHeader(name) {
if (typeof name !== 'string') 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(); name = name.trim().toLowerCase();
return Object.prototype.hasOwnProperty.call(this[kHeaders], name); return Object.prototype.hasOwnProperty.call(this[kHeaders], name);
@ -469,10 +480,10 @@ class Http2ServerResponse extends Stream {
removeHeader(name) { removeHeader(name) {
if (typeof name !== 'string') 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) if (this[kStream].headersSent)
throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); throw new ERR_HTTP2_HEADERS_SENT();
name = name.trim().toLowerCase(); name = name.trim().toLowerCase();
delete this[kHeaders][name]; delete this[kHeaders][name];
@ -480,10 +491,10 @@ class Http2ServerResponse extends Stream {
setHeader(name, value) { setHeader(name, value) {
if (typeof name !== 'string') 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) if (this[kStream].headersSent)
throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); throw new ERR_HTTP2_HEADERS_SENT();
this[kSetHeader](name, value); this[kSetHeader](name, value);
} }
@ -514,9 +525,9 @@ class Http2ServerResponse extends Stream {
const state = this[kState]; const state = this[kState];
if (state.closed) if (state.closed)
throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); throw new ERR_HTTP2_INVALID_STREAM();
if (this[kStream].headersSent) if (this[kStream].headersSent)
throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); throw new ERR_HTTP2_HEADERS_SENT();
if (typeof statusMessage === 'string') if (typeof statusMessage === 'string')
statusMessageWarn(); statusMessageWarn();
@ -544,7 +555,7 @@ class Http2ServerResponse extends Stream {
} }
if (this[kState].closed) { if (this[kState].closed) {
const err = new errors.Error('ERR_HTTP2_INVALID_STREAM'); const err = new ERR_HTTP2_INVALID_STREAM();
if (typeof cb === 'function') if (typeof cb === 'function')
process.nextTick(cb, err); process.nextTick(cb, err);
else else
@ -614,9 +625,9 @@ class Http2ServerResponse extends Stream {
createPushResponse(headers, callback) { createPushResponse(headers, callback) {
if (typeof callback !== 'function') if (typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
if (this[kState].closed) { if (this[kState].closed) {
process.nextTick(callback, new errors.Error('ERR_HTTP2_INVALID_STREAM')); process.nextTick(callback, new ERR_HTTP2_INVALID_STREAM());
return; return;
} }
this[kStream].pushStream(headers, {}, (err, stream, headers, options) => { this[kStream].pushStream(headers, {}, (err, stream, headers, options) => {

View File

@ -14,7 +14,47 @@ const net = require('net');
const tls = require('tls'); const tls = require('tls');
const util = require('util'); const util = require('util');
const fs = require('fs'); 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 { StreamWrap } = require('_stream_wrap');
const { Duplex } = require('stream'); const { Duplex } = require('stream');
const { URL } = require('url'); const { URL } = require('url');
@ -437,7 +477,7 @@ function onGoawayData(code, lastStreamID, buf) {
// goaway using NGHTTP2_NO_ERROR because there was no error // goaway using NGHTTP2_NO_ERROR because there was no error
// condition on this side of the session that caused the // condition on this side of the session that caused the
// shutdown. // shutdown.
session.destroy(new errors.Error('ERR_HTTP2_SESSION_ERROR', code), session.destroy(new ERR_HTTP2_SESSION_ERROR(code),
{ errorCode: NGHTTP2_NO_ERROR }); { errorCode: NGHTTP2_NO_ERROR });
} }
} }
@ -468,7 +508,7 @@ function requestOnConnect(headers, options) {
// If the session was closed while waiting for the connect, destroy // If the session was closed while waiting for the connect, destroy
// the stream and do not continue with the request. // the stream and do not continue with the request.
if (session.closed) { if (session.closed) {
const err = new errors.Error('ERR_HTTP2_GOAWAY_SESSION'); const err = new ERR_HTTP2_GOAWAY_SESSION();
this.destroy(err); this.destroy(err);
return; return;
} }
@ -506,11 +546,11 @@ function requestOnConnect(headers, options) {
let err; let err;
switch (ret) { switch (ret) {
case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE: 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); this.destroy(err);
break; break;
case NGHTTP2_ERR_INVALID_ARGUMENT: case NGHTTP2_ERR_INVALID_ARGUMENT:
err = new errors.Error('ERR_HTTP2_STREAM_SELF_DEPENDENCY'); err = new ERR_HTTP2_STREAM_SELF_DEPENDENCY();
this.destroy(err); this.destroy(err);
break; break;
default: default:
@ -533,33 +573,25 @@ function validatePriorityOptions(options) {
if (options.weight === undefined) { if (options.weight === undefined) {
options.weight = NGHTTP2_DEFAULT_WEIGHT; options.weight = NGHTTP2_DEFAULT_WEIGHT;
} else if (typeof options.weight !== 'number') { } else if (typeof options.weight !== 'number') {
err = new errors.TypeError('ERR_INVALID_OPT_VALUE', err = new ERR_INVALID_OPT_VALUE('weight', options.weight);
'weight',
options.weight);
} }
if (options.parent === undefined) { if (options.parent === undefined) {
options.parent = 0; options.parent = 0;
} else if (typeof options.parent !== 'number' || options.parent < 0) { } else if (typeof options.parent !== 'number' || options.parent < 0) {
err = new errors.TypeError('ERR_INVALID_OPT_VALUE', err = new ERR_INVALID_OPT_VALUE('parent', options.parent);
'parent',
options.parent);
} }
if (options.exclusive === undefined) { if (options.exclusive === undefined) {
options.exclusive = false; options.exclusive = false;
} else if (typeof options.exclusive !== 'boolean') { } else if (typeof options.exclusive !== 'boolean') {
err = new errors.TypeError('ERR_INVALID_OPT_VALUE', err = new ERR_INVALID_OPT_VALUE('exclusive', options.exclusive);
'exclusive',
options.exclusive);
} }
if (options.silent === undefined) { if (options.silent === undefined) {
options.silent = false; options.silent = false;
} else if (typeof options.silent !== 'boolean') { } else if (typeof options.silent !== 'boolean') {
err = new errors.TypeError('ERR_INVALID_OPT_VALUE', err = new ERR_INVALID_OPT_VALUE('silent', options.silent);
'silent',
options.silent);
} }
if (err) { if (err) {
@ -587,7 +619,7 @@ function settingsCallback(cb, ack, duration) {
} else { } else {
debug(`Http2Session ${sessionName(this[kType])}: settings canceled`); debug(`Http2Session ${sessionName(this[kType])}: settings canceled`);
if (typeof cb === 'function') 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](); this[kUpdateTimer]();
updateSettingsBuffer(settings); updateSettingsBuffer(settings);
if (!this[kHandle].settings(settingsCallback.bind(this, callback))) { 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 'read':
case 'resume': case 'resume':
case 'write': case 'write':
throw new errors.Error('ERR_HTTP2_NO_SOCKET_MANIPULATION'); throw new ERR_HTTP2_NO_SOCKET_MANIPULATION();
default: default:
const socket = session[kSocket]; const socket = session[kSocket];
const value = socket[prop]; const value = socket[prop];
@ -668,7 +700,7 @@ const proxySocketHandler = {
case 'read': case 'read':
case 'resume': case 'resume':
case 'write': case 'write':
throw new errors.Error('ERR_HTTP2_NO_SOCKET_MANIPULATION'); throw new ERR_HTTP2_NO_SOCKET_MANIPULATION();
default: default:
session[kSocket][prop] = value; session[kSocket][prop] = value;
return true; return true;
@ -684,7 +716,7 @@ const proxySocketHandler = {
// data received on the PING acknowlegement. // data received on the PING acknowlegement.
function pingCallback(cb) { function pingCallback(cb) {
return function pingCallback(ack, duration, payload) { 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); cb(err, duration, payload);
}; };
} }
@ -716,8 +748,8 @@ function validateSettings(settings) {
0, kMaxInt); 0, kMaxInt);
if (settings.enablePush !== undefined && if (settings.enablePush !== undefined &&
typeof settings.enablePush !== 'boolean') { typeof settings.enablePush !== 'boolean') {
const err = new errors.TypeError('ERR_HTTP2_INVALID_SETTING_VALUE', const err = new ERR_HTTP2_INVALID_SETTING_VALUE('enablePush',
'enablePush', settings.enablePush); settings.enablePush);
err.actual = settings.enablePush; err.actual = settings.enablePush;
Error.captureStackTrace(err, 'validateSettings'); Error.captureStackTrace(err, 'validateSettings');
throw err; throw err;
@ -838,7 +870,7 @@ class Http2Session extends EventEmitter {
// then it has already been bound to an Http2Session instance // then it has already been bound to an Http2Session instance
// and cannot be attached again. // and cannot be attached again.
if (socket[kSession] !== undefined) if (socket[kSession] !== undefined)
throw new errors.Error('ERR_HTTP2_SOCKET_BOUND'); throw new ERR_HTTP2_SOCKET_BOUND();
socket[kSession] = this; socket[kSession] = this;
@ -945,13 +977,12 @@ class Http2Session extends EventEmitter {
// value also needs to be larger than the current next stream ID. // value also needs to be larger than the current next stream ID.
setNextStreamID(id) { setNextStreamID(id) {
if (this.destroyed) if (this.destroyed)
throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); throw new ERR_HTTP2_INVALID_SESSION();
if (typeof id !== 'number') 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) if (id <= 0 || id > kMaxStreams)
throw new errors.RangeError('ERR_OUT_OF_RANGE', 'id', throw new ERR_OUT_OF_RANGE('id', `> 0 and <= ${kMaxStreams}`, id);
`> 0 and <= ${kMaxStreams}`, id);
this[kHandle].setNextStreamID(id); this[kHandle].setNextStreamID(id);
} }
@ -960,22 +991,21 @@ class Http2Session extends EventEmitter {
// cancelled error and a duration of 0.0. // cancelled error and a duration of 0.0.
ping(payload, callback) { ping(payload, callback) {
if (this.destroyed) if (this.destroyed)
throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); throw new ERR_HTTP2_INVALID_SESSION();
if (typeof payload === 'function') { if (typeof payload === 'function') {
callback = payload; callback = payload;
payload = undefined; payload = undefined;
} }
if (payload && !isArrayBufferView(payload)) { if (payload && !isArrayBufferView(payload)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('payload',
'payload', ['Buffer', 'TypedArray', 'DataView']);
['Buffer', 'TypedArray', 'DataView']);
} }
if (payload && payload.length !== 8) { if (payload && payload.length !== 8) {
throw new errors.RangeError('ERR_HTTP2_PING_LENGTH'); throw new ERR_HTTP2_PING_LENGTH();
} }
if (typeof callback !== 'function') if (typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
const cb = pingCallback(callback); const cb = pingCallback(callback);
if (this.connecting || this.closed) { if (this.connecting || this.closed) {
@ -1060,12 +1090,12 @@ class Http2Session extends EventEmitter {
// Submits a SETTINGS frame to be sent to the remote peer. // Submits a SETTINGS frame to be sent to the remote peer.
settings(settings, callback) { settings(settings, callback) {
if (this.destroyed) if (this.destroyed)
throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); throw new ERR_HTTP2_INVALID_SESSION();
assertIsObject(settings, 'settings'); assertIsObject(settings, 'settings');
settings = validateSettings(settings); settings = validateSettings(settings);
if (callback && typeof callback !== 'function') if (callback && typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
debug(`Http2Session ${sessionName(this[kType])}: sending settings`); debug(`Http2Session ${sessionName(this[kType])}: sending settings`);
this[kState].pendingAck++; this[kState].pendingAck++;
@ -1084,19 +1114,17 @@ class Http2Session extends EventEmitter {
// be rejected automatically. // be rejected automatically.
goaway(code = NGHTTP2_NO_ERROR, lastStreamID = 0, opaqueData) { goaway(code = NGHTTP2_NO_ERROR, lastStreamID = 0, opaqueData) {
if (this.destroyed) if (this.destroyed)
throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); throw new ERR_HTTP2_INVALID_SESSION();
if (opaqueData !== undefined && !isArrayBufferView(opaqueData)) { if (opaqueData !== undefined && !isArrayBufferView(opaqueData)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('opaqueData',
'opaqueData', ['Buffer', 'TypedArray', 'DataView']);
['Buffer', 'TypedArray', 'DataView']);
} }
if (typeof code !== 'number') { 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') { if (typeof lastStreamID !== 'number') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('lastStreamID', 'number');
'lastStreamID', 'number');
} }
const goawayFn = submitGoaway.bind(this, code, lastStreamID, opaqueData); const goawayFn = submitGoaway.bind(this, code, lastStreamID, opaqueData);
@ -1118,7 +1146,7 @@ class Http2Session extends EventEmitter {
code = error; code = error;
error = error =
code !== NGHTTP2_NO_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) if (code === undefined && error != null)
code = NGHTTP2_INTERNAL_ERROR; code = NGHTTP2_INTERNAL_ERROR;
@ -1131,7 +1159,7 @@ class Http2Session extends EventEmitter {
this.removeAllListeners('timeout'); this.removeAllListeners('timeout');
// Destroy any pending and open streams // Destroy any pending and open streams
const cancel = new errors.Error('ERR_HTTP2_STREAM_CANCEL'); const cancel = new ERR_HTTP2_STREAM_CANCEL();
if (error) { if (error) {
cancel.cause = error; cancel.cause = error;
if (typeof error.message === 'string') if (typeof error.message === 'string')
@ -1265,7 +1293,7 @@ class ServerHttp2Session extends Http2Session {
// API is provided for that. // API is provided for that.
altsvc(alt, originOrStream) { altsvc(alt, originOrStream) {
if (this.destroyed) if (this.destroyed)
throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); throw new ERR_HTTP2_INVALID_SESSION();
let stream = 0; let stream = 0;
let origin; let origin;
@ -1273,10 +1301,10 @@ class ServerHttp2Session extends Http2Session {
if (typeof originOrStream === 'string') { if (typeof originOrStream === 'string') {
origin = (new URL(originOrStream)).origin; origin = (new URL(originOrStream)).origin;
if (origin === 'null') if (origin === 'null')
throw new errors.TypeError('ERR_HTTP2_ALTSVC_INVALID_ORIGIN'); throw new ERR_HTTP2_ALTSVC_INVALID_ORIGIN();
} else if (typeof originOrStream === 'number') { } else if (typeof originOrStream === 'number') {
if (originOrStream >>> 0 !== originOrStream || originOrStream === 0) if (originOrStream >>> 0 !== originOrStream || originOrStream === 0)
throw new errors.RangeError('ERR_OUT_OF_RANGE', 'originOrStream'); throw new ERR_OUT_OF_RANGE('originOrStream');
stream = originOrStream; stream = originOrStream;
} else if (originOrStream !== undefined) { } else if (originOrStream !== undefined) {
// Allow origin to be passed a URL or object with origin property // 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 // ensure they are doing the right thing or the payload data will
// be invalid. // be invalid.
if (typeof origin !== 'string') { if (typeof origin !== 'string') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'originOrStream', throw new ERR_INVALID_ARG_TYPE('originOrStream',
['string', 'number', 'URL', 'object']); ['string', 'number', 'URL', 'object']);
} else if (origin === 'null' || origin.length === 0) { } 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') 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)) if (!kQuotedString.test(alt))
throw new errors.TypeError('ERR_INVALID_CHAR', 'alt'); throw new ERR_INVALID_CHAR('alt');
// Max length permitted for ALTSVC // Max length permitted for ALTSVC
if ((alt.length + (origin !== undefined ? origin.length : 0)) > 16382) 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); this[kHandle].altsvc(stream, origin || '', alt);
} }
@ -1323,10 +1351,10 @@ class ClientHttp2Session extends Http2Session {
debug(`Http2Session ${sessionName(this[kType])}: initiating request`); debug(`Http2Session ${sessionName(this[kType])}: initiating request`);
if (this.destroyed) if (this.destroyed)
throw new errors.Error('ERR_HTTP2_INVALID_SESSION'); throw new ERR_HTTP2_INVALID_SESSION();
if (this.closed) if (this.closed)
throw new errors.Error('ERR_HTTP2_GOAWAY_SESSION'); throw new ERR_HTTP2_GOAWAY_SESSION();
this[kUpdateTimer](); this[kUpdateTimer]();
@ -1350,11 +1378,11 @@ class ClientHttp2Session extends Http2Session {
headers[HTTP2_HEADER_PATH] = '/'; headers[HTTP2_HEADER_PATH] = '/';
} else { } else {
if (headers[HTTP2_HEADER_AUTHORITY] === undefined) 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) 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) if (headers[HTTP2_HEADER_PATH] !== undefined)
throw new errors.Error('ERR_HTTP2_CONNECT_PATH'); throw new ERR_HTTP2_CONNECT_PATH();
} }
validatePriorityOptions(options); validatePriorityOptions(options);
@ -1365,16 +1393,12 @@ class ClientHttp2Session extends Http2Session {
// preference. // preference.
options.endStream = isPayloadMeaningless(headers[HTTP2_HEADER_METHOD]); options.endStream = isPayloadMeaningless(headers[HTTP2_HEADER_METHOD]);
} else if (typeof options.endStream !== 'boolean') { } else if (typeof options.endStream !== 'boolean') {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('endStream', options.endStream);
'endStream',
options.endStream);
} }
if (options.getTrailers !== undefined && if (options.getTrailers !== undefined &&
typeof options.getTrailers !== 'function') { typeof options.getTrailers !== 'function') {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('getTrailers', options.getTrailers);
'getTrailers',
options.getTrailers);
} }
const headersList = mapToHeaders(headers); const headersList = mapToHeaders(headers);
@ -1653,7 +1677,7 @@ class Http2Stream extends Duplex {
req.async = false; req.async = false;
const err = createWriteReq(req, handle, data, encoding); const err = createWriteReq(req, handle, data, encoding);
if (err) if (err)
throw errors.errnoException(err, 'write', req.error); throw errnoException(err, 'write', req.error);
trackWriteState(this, req.bytes); trackWriteState(this, req.bytes);
} }
@ -1696,7 +1720,7 @@ class Http2Stream extends Duplex {
} }
const err = handle.writev(req, chunks); const err = handle.writev(req, chunks);
if (err) if (err)
throw errors.errnoException(err, 'write', req.error); throw errnoException(err, 'write', req.error);
trackWriteState(this, req.bytes); trackWriteState(this, req.bytes);
} }
@ -1731,7 +1755,7 @@ class Http2Stream extends Duplex {
priority(options) { priority(options) {
if (this.destroyed) if (this.destroyed)
throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); throw new ERR_HTTP2_INVALID_STREAM();
assertIsObject(options, 'options'); assertIsObject(options, 'options');
options = Object.assign({}, options); options = Object.assign({}, options);
@ -1767,11 +1791,11 @@ class Http2Stream extends Duplex {
// but no DATA and HEADERS frames may be sent. // but no DATA and HEADERS frames may be sent.
close(code = NGHTTP2_NO_ERROR, callback) { close(code = NGHTTP2_NO_ERROR, callback) {
if (typeof code !== 'number') 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) 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') if (callback !== undefined && typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
// Clear timeout and remove timeout listeners // Clear timeout and remove timeout listeners
this.setTimeout(0); this.setTimeout(0);
@ -1850,8 +1874,7 @@ class Http2Stream extends Duplex {
// abort and is already covered by aborted event, also allows more // abort and is already covered by aborted event, also allows more
// seamless compatibility with http1 // seamless compatibility with http1
if (err == null && code !== NGHTTP2_NO_ERROR && code !== NGHTTP2_CANCEL) if (err == null && code !== NGHTTP2_NO_ERROR && code !== NGHTTP2_CANCEL)
err = new errors.Error('ERR_HTTP2_STREAM_ERROR', err = new ERR_HTTP2_STREAM_ERROR(nameForErrorCode[code] || code);
nameForErrorCode[code] || code);
this[kSession] = undefined; this[kSession] = undefined;
this[kHandle] = undefined; this[kHandle] = undefined;
@ -1900,8 +1923,7 @@ function processHeaders(headers) {
// This will have an impact on the compatibility layer for anyone using // This will have an impact on the compatibility layer for anyone using
// non-standard, non-compliant status codes. // non-standard, non-compliant status codes.
if (statusCode < 200 || statusCode > 599) if (statusCode < 200 || statusCode > 599)
throw new errors.RangeError('ERR_HTTP2_STATUS_INVALID', throw new ERR_HTTP2_STATUS_INVALID(headers[HTTP2_HEADER_STATUS]);
headers[HTTP2_HEADER_STATUS]);
return headers; 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 // In either case, we do not want to continue because the we are shutting
// down and should not attempt to send any data. // down and should not attempt to send any data.
if (this.destroyed || this.closed) { if (this.destroyed || this.closed) {
this.destroy(new errors.Error('ERR_HTTP2_INVALID_STREAM')); this.destroy(new ERR_HTTP2_INVALID_STREAM());
return; return;
} }
@ -1986,7 +2008,7 @@ function doSendFileFD(session, options, fd, headers, streamOptions, err, stat) {
} }
if (!stat.isFile()) { if (!stat.isFile()) {
const err = new errors.Error('ERR_HTTP2_SEND_FILE'); const err = new ERR_HTTP2_SEND_FILE();
if (onError) if (onError)
onError(err); onError(err);
else else
@ -1996,7 +2018,7 @@ function doSendFileFD(session, options, fd, headers, streamOptions, err, stat) {
if (this.destroyed || this.closed) { if (this.destroyed || this.closed) {
tryClose(fd); tryClose(fd);
this.destroy(new errors.Error('ERR_HTTP2_INVALID_STREAM')); this.destroy(new ERR_HTTP2_INVALID_STREAM());
return; return;
} }
@ -2079,7 +2101,7 @@ class ServerHttp2Stream extends Http2Stream {
// Http2Stream for the push stream. // Http2Stream for the push stream.
pushStream(headers, options, callback) { pushStream(headers, options, callback) {
if (!this.pushAllowed) if (!this.pushAllowed)
throw new errors.Error('ERR_HTTP2_PUSH_DISABLED'); throw new ERR_HTTP2_PUSH_DISABLED();
const session = this[kSession]; const session = this[kSession];
@ -2094,7 +2116,7 @@ class ServerHttp2Stream extends Http2Stream {
} }
if (typeof callback !== 'function') if (typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
assertIsObject(options, 'options'); assertIsObject(options, 'options');
options = Object.assign({}, options); options = Object.assign({}, options);
@ -2128,10 +2150,10 @@ class ServerHttp2Stream extends Http2Stream {
if (typeof ret === 'number') { if (typeof ret === 'number') {
switch (ret) { switch (ret) {
case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE: case NGHTTP2_ERR_STREAM_ID_NOT_AVAILABLE:
err = new errors.Error('ERR_HTTP2_OUT_OF_STREAMS'); err = new ERR_HTTP2_OUT_OF_STREAMS();
break; break;
case NGHTTP2_ERR_STREAM_CLOSED: case NGHTTP2_ERR_STREAM_CLOSED:
err = new errors.Error('ERR_HTTP2_INVALID_STREAM'); err = new ERR_HTTP2_INVALID_STREAM();
break; break;
default: default:
err = new NghttpError(ret); err = new NghttpError(ret);
@ -2157,9 +2179,9 @@ class ServerHttp2Stream extends Http2Stream {
// Initiate a response on this Http2Stream // Initiate a response on this Http2Stream
respond(headers, options) { respond(headers, options) {
if (this.destroyed || this.closed) if (this.destroyed || this.closed)
throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); throw new ERR_HTTP2_INVALID_STREAM();
if (this.headersSent) if (this.headersSent)
throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); throw new ERR_HTTP2_HEADERS_SENT();
const state = this[kState]; const state = this[kState];
@ -2179,9 +2201,7 @@ class ServerHttp2Stream extends Http2Stream {
if (options.getTrailers !== undefined) { if (options.getTrailers !== undefined) {
if (typeof options.getTrailers !== 'function') { if (typeof options.getTrailers !== 'function') {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('getTrailers', options.getTrailers);
'getTrailers',
options.getTrailers);
} }
streamOptions |= STREAM_OPTION_GET_TRAILERS; streamOptions |= STREAM_OPTION_GET_TRAILERS;
state.getTrailers = options.getTrailers; state.getTrailers = options.getTrailers;
@ -2224,9 +2244,9 @@ class ServerHttp2Stream extends Http2Stream {
// reset with an error code. // reset with an error code.
respondWithFD(fd, headers, options) { respondWithFD(fd, headers, options) {
if (this.destroyed || this.closed) if (this.destroyed || this.closed)
throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); throw new ERR_HTTP2_INVALID_STREAM();
if (this.headersSent) if (this.headersSent)
throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); throw new ERR_HTTP2_HEADERS_SENT();
const session = this[kSession]; const session = this[kSession];
@ -2234,36 +2254,27 @@ class ServerHttp2Stream extends Http2Stream {
options = Object.assign({}, options); options = Object.assign({}, options);
if (options.offset !== undefined && typeof options.offset !== 'number') if (options.offset !== undefined && typeof options.offset !== 'number')
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('offset', options.offset);
'offset',
options.offset);
if (options.length !== undefined && typeof options.length !== 'number') if (options.length !== undefined && typeof options.length !== 'number')
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('length', options.length);
'length',
options.length);
if (options.statCheck !== undefined && if (options.statCheck !== undefined &&
typeof options.statCheck !== 'function') { typeof options.statCheck !== 'function') {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('statCheck', options.statCheck);
'statCheck',
options.statCheck);
} }
let streamOptions = 0; let streamOptions = 0;
if (options.getTrailers !== undefined) { if (options.getTrailers !== undefined) {
if (typeof options.getTrailers !== 'function') { if (typeof options.getTrailers !== 'function') {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('getTrailers', options.getTrailers);
'getTrailers',
options.getTrailers);
} }
streamOptions |= STREAM_OPTION_GET_TRAILERS; streamOptions |= STREAM_OPTION_GET_TRAILERS;
this[kState].getTrailers = options.getTrailers; this[kState].getTrailers = options.getTrailers;
} }
if (typeof fd !== 'number') if (typeof fd !== 'number')
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('fd', 'number');
'fd', 'number');
debug(`Http2Stream ${this[kID]} [Http2Session ` + debug(`Http2Stream ${this[kID]} [Http2Session ` +
`${sessionName(session[kType])}]: initiating response`); `${sessionName(session[kType])}]: initiating response`);
@ -2275,7 +2286,7 @@ class ServerHttp2Stream extends Http2Stream {
if (statusCode === HTTP_STATUS_NO_CONTENT || if (statusCode === HTTP_STATUS_NO_CONTENT ||
statusCode === HTTP_STATUS_RESET_CONTENT || statusCode === HTTP_STATUS_RESET_CONTENT ||
statusCode === HTTP_STATUS_NOT_MODIFIED) { 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) { if (options.statCheck !== undefined) {
@ -2300,36 +2311,28 @@ class ServerHttp2Stream extends Http2Stream {
// file details are sent. // file details are sent.
respondWithFile(path, headers, options) { respondWithFile(path, headers, options) {
if (this.destroyed || this.closed) if (this.destroyed || this.closed)
throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); throw new ERR_HTTP2_INVALID_STREAM();
if (this.headersSent) if (this.headersSent)
throw new errors.Error('ERR_HTTP2_HEADERS_SENT'); throw new ERR_HTTP2_HEADERS_SENT();
assertIsObject(options, 'options'); assertIsObject(options, 'options');
options = Object.assign({}, options); options = Object.assign({}, options);
if (options.offset !== undefined && typeof options.offset !== 'number') if (options.offset !== undefined && typeof options.offset !== 'number')
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('offset', options.offset);
'offset',
options.offset);
if (options.length !== undefined && typeof options.length !== 'number') if (options.length !== undefined && typeof options.length !== 'number')
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('length', options.length);
'length',
options.length);
if (options.statCheck !== undefined && if (options.statCheck !== undefined &&
typeof options.statCheck !== 'function') { typeof options.statCheck !== 'function') {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('statCheck', options.statCheck);
'statCheck',
options.statCheck);
} }
let streamOptions = 0; let streamOptions = 0;
if (options.getTrailers !== undefined) { if (options.getTrailers !== undefined) {
if (typeof options.getTrailers !== 'function') { if (typeof options.getTrailers !== 'function') {
throw new errors.TypeError('ERR_INVALID_OPT_VALUE', throw new ERR_INVALID_OPT_VALUE('getTrailers', options.getTrailers);
'getTrailers',
options.getTrailers);
} }
streamOptions |= STREAM_OPTION_GET_TRAILERS; streamOptions |= STREAM_OPTION_GET_TRAILERS;
this[kState].getTrailers = options.getTrailers; this[kState].getTrailers = options.getTrailers;
@ -2347,7 +2350,7 @@ class ServerHttp2Stream extends Http2Stream {
if (statusCode === HTTP_STATUS_NO_CONTENT || if (statusCode === HTTP_STATUS_NO_CONTENT ||
statusCode === HTTP_STATUS_RESET_CONTENT || statusCode === HTTP_STATUS_RESET_CONTENT ||
statusCode === HTTP_STATUS_NOT_MODIFIED) { 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', fs.open(path, 'r',
@ -2363,9 +2366,9 @@ class ServerHttp2Stream extends Http2Stream {
// headers are sent, or an error will be thrown. // headers are sent, or an error will be thrown.
additionalHeaders(headers) { additionalHeaders(headers) {
if (this.destroyed || this.closed) if (this.destroyed || this.closed)
throw new errors.Error('ERR_HTTP2_INVALID_STREAM'); throw new ERR_HTTP2_INVALID_STREAM();
if (this.headersSent) if (this.headersSent)
throw new errors.Error('ERR_HTTP2_HEADERS_AFTER_RESPOND'); throw new ERR_HTTP2_HEADERS_AFTER_RESPOND();
assertIsObject(headers, 'headers'); assertIsObject(headers, 'headers');
headers = Object.assign(Object.create(null), headers); headers = Object.assign(Object.create(null), headers);
@ -2377,10 +2380,9 @@ class ServerHttp2Stream extends Http2Stream {
if (headers[HTTP2_HEADER_STATUS] != null) { if (headers[HTTP2_HEADER_STATUS] != null) {
const statusCode = headers[HTTP2_HEADER_STATUS] |= 0; const statusCode = headers[HTTP2_HEADER_STATUS] |= 0;
if (statusCode === HTTP_STATUS_SWITCHING_PROTOCOLS) 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) { if (statusCode < 100 || statusCode >= 200) {
throw new errors.RangeError('ERR_HTTP2_INVALID_INFO_STATUS', throw new ERR_HTTP2_INVALID_INFO_STATUS(headers[HTTP2_HEADER_STATUS]);
headers[HTTP2_HEADER_STATUS]);
} }
} }
@ -2435,7 +2437,7 @@ const setTimeout = {
if (msecs === 0) { if (msecs === 0) {
if (callback !== undefined) { if (callback !== undefined) {
if (typeof callback !== 'function') if (typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
this.removeListener('timeout', callback); this.removeListener('timeout', callback);
} }
} else { } else {
@ -2444,7 +2446,7 @@ const setTimeout = {
if (callback !== undefined) { if (callback !== undefined) {
if (typeof callback !== 'function') if (typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
this.once('timeout', callback); this.once('timeout', callback);
} }
} }
@ -2589,7 +2591,7 @@ class Http2SecureServer extends TLSServer {
this.timeout = msecs; this.timeout = msecs;
if (callback !== undefined) { if (callback !== undefined) {
if (typeof callback !== 'function') if (typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
this.on('timeout', callback); this.on('timeout', callback);
} }
return this; return this;
@ -2610,7 +2612,7 @@ class Http2Server extends NETServer {
this.timeout = msecs; this.timeout = msecs;
if (callback !== undefined) { if (callback !== undefined) {
if (typeof callback !== 'function') if (typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
this.on('timeout', callback); this.on('timeout', callback);
} }
return this; return this;
@ -2632,8 +2634,7 @@ function socketOnClose() {
const session = this[kSession]; const session = this[kSession];
if (session !== undefined) { if (session !== undefined) {
debug(`Http2Session ${sessionName(session[kType])}: socket closed`); debug(`Http2Session ${sessionName(session[kType])}: socket closed`);
const err = session.connecting ? const err = session.connecting ? new ERR_SOCKET_CLOSED() : null;
new errors.Error('ERR_SOCKET_CLOSED') : null;
const state = session[kState]; const state = session[kState];
state.streams.forEach((stream) => stream.close(NGHTTP2_CANCEL)); state.streams.forEach((stream) => stream.close(NGHTTP2_CANCEL));
state.pendingStreams.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)); socket = tls.connect(port, host, initializeTLSOptions(options, host));
break; break;
default: 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 = {}) { function getUnpackedSettings(buf, options = {}) {
if (!isArrayBufferView(buf)) { if (!isArrayBufferView(buf)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'buf', throw new ERR_INVALID_ARG_TYPE('buf', ['Buffer', 'TypedArray', 'DataView']);
['Buffer', 'TypedArray', 'DataView']);
} }
if (buf.length % 6 !== 0) 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 = {}; const settings = {};
let offset = 0; let offset = 0;
while (offset < buf.length) { while (offset < buf.length) {

View File

@ -1,7 +1,13 @@
'use strict'; 'use strict';
const binding = process.binding('http2'); 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'); const kSocket = Symbol('socket');
@ -382,7 +388,7 @@ function isIllegalConnectionSpecificHeader(name, value) {
function assertValidPseudoHeader(key) { function assertValidPseudoHeader(key) {
if (!kValidPseudoHeaders.has(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); Error.captureStackTrace(err, assertValidPseudoHeader);
return err; return err;
} }
@ -390,14 +396,14 @@ function assertValidPseudoHeader(key) {
function assertValidPseudoHeaderResponse(key) { function assertValidPseudoHeaderResponse(key) {
if (key !== ':status') { 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); Error.captureStackTrace(err, assertValidPseudoHeaderResponse);
return err; return err;
} }
} }
function assertValidPseudoHeaderTrailer(key) { 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); Error.captureStackTrace(err, assertValidPseudoHeaderTrailer);
return err; return err;
} }
@ -426,14 +432,14 @@ function mapToHeaders(map,
break; break;
default: default:
if (isSingleValueHeader) if (isSingleValueHeader)
return new errors.Error('ERR_HTTP2_HEADER_SINGLE_VALUE', key); return new ERR_HTTP2_HEADER_SINGLE_VALUE(key);
} }
} else { } else {
value = String(value); value = String(value);
} }
if (isSingleValueHeader) { if (isSingleValueHeader) {
if (singles.has(key)) 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); singles.add(key);
} }
if (key[0] === ':') { if (key[0] === ':') {
@ -444,7 +450,7 @@ function mapToHeaders(map,
count++; count++;
} else { } else {
if (isIllegalConnectionSpecificHeader(key, value)) { if (isIllegalConnectionSpecificHeader(key, value)) {
return new errors.Error('ERR_HTTP2_INVALID_CONNECTION_HEADERS', key); return new ERR_HTTP2_INVALID_CONNECTION_HEADERS(key);
} }
if (isArray) { if (isArray) {
for (var k = 0; k < value.length; k++) { for (var k = 0; k < value.length; k++) {
@ -476,7 +482,7 @@ function assertIsObject(value, name, types = 'Object') {
(value === null || (value === null ||
typeof value !== 'object' || typeof value !== 'object' ||
Array.isArray(value))) { 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); Error.captureStackTrace(err, assertIsObject);
throw err; throw err;
} }
@ -485,8 +491,7 @@ function assertIsObject(value, name, types = 'Object') {
function assertWithinRange(name, value, min = 0, max = Infinity) { function assertWithinRange(name, value, min = 0, max = Infinity) {
if (value !== undefined && if (value !== undefined &&
(typeof value !== 'number' || value < min || value > max)) { (typeof value !== 'number' || value < min || value > max)) {
const err = new errors.RangeError('ERR_HTTP2_INVALID_SETTING_VALUE', const err = new ERR_HTTP2_INVALID_SETTING_VALUE.RangeError(name, value);
name, value);
err.min = min; err.min = min;
err.max = max; err.max = max;
err.actual = value; err.actual = value;

View File

@ -7,7 +7,11 @@ const { NativeModule, internalBinding } = require('internal/bootstrap_loaders');
const { extname } = require('path'); const { extname } = require('path');
const { realpathSync } = require('fs'); const { realpathSync } = require('fs');
const preserveSymlinks = !!process.binding('config').preserveSymlinks; 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 { resolve: moduleWrapResolve } = internalBinding('module_wrap');
const StringStartsWith = Function.call.bind(String.prototype.startsWith); const StringStartsWith = Function.call.bind(String.prototype.startsWith);
const { getURLFromFilePath, getPathFromURL } = require('internal/url'); const { getURLFromFilePath, getPathFromURL } = require('internal/url');
@ -17,7 +21,7 @@ const realpathCache = new Map();
function search(target, base) { function search(target, base) {
if (base === undefined) { if (base === undefined) {
// We cannot search without a base. // We cannot search without a base.
throw new errors.Error('ERR_MISSING_MODULE', target); throw new ERR_MISSING_MODULE(target);
} }
try { try {
return moduleWrapResolve(target, base); return moduleWrapResolve(target, base);
@ -30,8 +34,7 @@ function search(target, base) {
tmpMod.paths = CJSmodule._nodeModulePaths( tmpMod.paths = CJSmodule._nodeModulePaths(
new URL('./', questionedBase).pathname); new URL('./', questionedBase).pathname);
const found = CJSmodule._resolveFilename(target, tmpMod); const found = CJSmodule._resolveFilename(target, tmpMod);
error = new errors.Error('ERR_MODULE_RESOLUTION_LEGACY', target, error = new ERR_MODULE_RESOLUTION_LEGACY(target, base, found);
base, found);
} catch (problemChecking) { } catch (problemChecking) {
// ignore // ignore
} }
@ -84,7 +87,7 @@ function resolve(specifier, parentURL) {
if (isMain) if (isMain)
format = 'cjs'; format = 'cjs';
else else
throw new errors.Error('ERR_UNKNOWN_FILE_EXTENSION', url.pathname); throw new ERR_UNKNOWN_FILE_EXTENSION(url.pathname);
} }
return { url: `${url}`, format }; return { url: `${url}`, format };

View File

@ -1,6 +1,11 @@
'use strict'; '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 ModuleMap = require('internal/loader/ModuleMap');
const ModuleJob = require('internal/loader/ModuleJob'); const ModuleJob = require('internal/loader/ModuleJob');
const defaultResolve = require('internal/loader/DefaultResolve'); const defaultResolve = require('internal/loader/DefaultResolve');
@ -44,22 +49,22 @@ class Loader {
async resolve(specifier, parentURL) { async resolve(specifier, parentURL) {
const isMain = parentURL === undefined; const isMain = parentURL === undefined;
if (!isMain && typeof parentURL !== 'string') 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 } = const { url, format } =
await this._resolve(specifier, parentURL, defaultResolve); await this._resolve(specifier, parentURL, defaultResolve);
if (typeof url !== 'string') 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') 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') if (format === 'builtin')
return { url: `node:${url}`, format }; return { url: `node:${url}`, format };
if (format !== 'dynamic' && !url.startsWith('file:')) 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 }; return { url, format };
} }
@ -87,7 +92,7 @@ class Loader {
let loaderInstance; let loaderInstance;
if (format === 'dynamic') { if (format === 'dynamic') {
if (typeof this._dynamicInstantiate !== 'function') if (typeof this._dynamicInstantiate !== 'function')
throw new errors.Error('ERR_MISSING_DYNAMIC_INTSTANTIATE_HOOK'); throw new ERR_MISSING_DYNAMIC_INTSTANTIATE_HOOK();
loaderInstance = async (url) => { loaderInstance = async (url) => {
debug(`Translating dynamic ${url}`); debug(`Translating dynamic ${url}`);
@ -99,7 +104,7 @@ class Loader {
}; };
} else { } else {
if (!translators.has(format)) if (!translators.has(format))
throw new errors.RangeError('ERR_UNKNOWN_MODULE_FORMAT', format); throw new ERR_UNKNOWN_MODULE_FORMAT(format);
loaderInstance = translators.get(format); loaderInstance = translators.get(format);
} }

View File

@ -3,29 +3,29 @@
const ModuleJob = require('internal/loader/ModuleJob'); const ModuleJob = require('internal/loader/ModuleJob');
const { SafeMap } = require('internal/safe_globals'); const { SafeMap } = require('internal/safe_globals');
const debug = require('util').debuglog('esm'); 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 // Tracks the state of the loader-level module cache
class ModuleMap extends SafeMap { class ModuleMap extends SafeMap {
get(url) { get(url) {
if (typeof url !== 'string') { 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); return super.get(url);
} }
set(url, job) { set(url, job) {
if (typeof url !== 'string') { 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) { 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`); debug(`Storing ${url} in ModuleMap`);
return super.set(url, job); return super.set(url, job);
} }
has(url) { has(url) {
if (typeof url !== 'string') { 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); return super.has(url);
} }

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
const errors = require('internal/errors'); const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes;
const { const {
CHAR_LINE_FEED, CHAR_LINE_FEED,
@ -25,8 +25,7 @@ function makeRequireFunction(mod) {
function resolve(request, options) { function resolve(request, options) {
if (typeof request !== 'string') { if (typeof request !== 'string') {
throw new errors.Error('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('request', 'string', request);
'request', 'string', request);
} }
return Module._resolveFilename(request, mod, false, options); return Module._resolveFilename(request, mod, false, options);
} }
@ -35,8 +34,7 @@ function makeRequireFunction(mod) {
function paths(request) { function paths(request) {
if (typeof request !== 'string') { if (typeof request !== 'string') {
throw new errors.Error('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('request', 'string', request);
'request', 'string', request);
} }
return Module._resolveLookupPaths(request, mod, true); return Module._resolveLookupPaths(request, mod, true);
} }

View File

@ -1,6 +1,16 @@
'use strict'; '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 util = require('util');
const constants = process.binding('constants').os.signals; const constants = process.binding('constants').os.signals;
const assert = require('assert').strict; const assert = require('assert').strict;
@ -8,7 +18,7 @@ const { deprecate } = require('internal/util');
process.assert = deprecate( process.assert = deprecate(
function(x, msg) { 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.', 'process.assert() is deprecated. Please use the `assert` module instead.',
'DEP0100'); 'DEP0100');
@ -31,20 +41,18 @@ function setup_cpuUsage() {
// If a previous value was passed in, ensure it has the correct shape. // If a previous value was passed in, ensure it has the correct shape.
if (prevValue) { if (prevValue) {
if (!previousValueIsValid(prevValue.user)) { if (!previousValueIsValid(prevValue.user)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('preValue.user', 'number');
'preValue.user', 'number');
} }
if (!previousValueIsValid(prevValue.system)) { if (!previousValueIsValid(prevValue.system)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('preValue.system', 'number');
'preValue.system', 'number');
} }
} }
// Call the native function to get the current values. // Call the native function to get the current values.
const errmsg = _cpuUsage(cpuValues); const errmsg = _cpuUsage(cpuValues);
if (errmsg) { 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. // If a previous value was passed in, return diff of current from previous.
@ -83,12 +91,10 @@ function setup_hrtime() {
if (time !== undefined) { if (time !== undefined) {
if (!Array.isArray(time)) { if (!Array.isArray(time)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'time', 'Array', throw new ERR_INVALID_ARG_TYPE('time', 'Array', time);
time);
} }
if (time.length !== 2) { if (time.length !== 2) {
throw new errors.TypeError('ERR_INVALID_ARRAY_LENGTH', 'time', 2, throw new ERR_INVALID_ARRAY_LENGTH('time', 2, time.length);
time.length);
} }
const sec = (hrValues[0] * 0x100000000 + hrValues[1]) - time[0]; const sec = (hrValues[0] * 0x100000000 + hrValues[1]) - time[0];
@ -158,7 +164,7 @@ function setupKillAndExit() {
// eslint-disable-next-line eqeqeq // eslint-disable-next-line eqeqeq
if (pid != (pid | 0)) { 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 // preserve null signal
@ -169,12 +175,12 @@ function setupKillAndExit() {
if (constants[sig]) { if (constants[sig]) {
err = process._kill(pid, constants[sig]); err = process._kill(pid, constants[sig]);
} else { } else {
throw new errors.TypeError('ERR_UNKNOWN_SIGNAL', sig); throw new ERR_UNKNOWN_SIGNAL(sig);
} }
} }
if (err) if (err)
throw errors.errnoException(err, 'kill'); throw errnoException(err, 'kill');
return true; return true;
}; };
@ -204,7 +210,7 @@ function setupSignalHandlers() {
const err = wrap.start(signum); const err = wrap.start(signum);
if (err) { if (err) {
wrap.close(); wrap.close();
throw errors.errnoException(err, 'uv_signal_start'); throw errnoException(err, 'uv_signal_start');
} }
signalWraps[type] = wrap; signalWraps[type] = wrap;
@ -256,11 +262,10 @@ function setupUncaughtExceptionCapture(exceptionHandlerState) {
return; return;
} }
if (typeof fn !== 'function') { if (typeof fn !== 'function') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'fn', throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'null']);
['Function', 'null']);
} }
if (exceptionHandlerState.captureFn !== 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; exceptionHandlerState.captureFn = fn;
shouldAbortOnUncaughtToggle[0] = 0; shouldAbortOnUncaughtToggle[0] = 0;

View File

@ -17,7 +17,7 @@ function setupNextTick() {
symbols: { async_id_symbol, trigger_async_id_symbol } symbols: { async_id_symbol, trigger_async_id_symbol }
} = require('internal/async_hooks'); } = require('internal/async_hooks');
const promises = require('internal/process/promises'); const promises = require('internal/process/promises');
const errors = require('internal/errors'); const { ERR_INVALID_CALLBACK } = require('internal/errors').codes;
const { emitPromiseRejectionWarnings } = promises; const { emitPromiseRejectionWarnings } = promises;
// tickInfo is used so that the C++ code in src/node.cc can // 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. // exit since the callback would not have a chance to be executed.
function nextTick(callback) { function nextTick(callback) {
if (typeof callback !== 'function') if (typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
if (process._exiting) if (process._exiting)
return; return;
@ -170,7 +170,7 @@ function setupNextTick() {
// about to exit since the callback would not have a chance to be executed. // about to exit since the callback would not have a chance to be executed.
function internalNextTick(triggerAsyncId, callback) { function internalNextTick(triggerAsyncId, callback) {
if (typeof callback !== 'function') if (typeof callback !== 'function')
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
// CHECK(Number.isSafeInteger(triggerAsyncId) || triggerAsyncId === null) // CHECK(Number.isSafeInteger(triggerAsyncId) || triggerAsyncId === null)
// CHECK(triggerAsyncId > 0 || triggerAsyncId === null) // CHECK(triggerAsyncId > 0 || triggerAsyncId === null)

View File

@ -1,6 +1,11 @@
'use strict'; '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; exports.setup = setupStdio;
@ -15,7 +20,7 @@ function setupStdio() {
stdout.destroySoon = stdout.destroy; stdout.destroySoon = stdout.destroy;
stdout._destroy = function(er, cb) { stdout._destroy = function(er, cb) {
// Avoid errors if we already emitted // Avoid errors if we already emitted
er = er || new errors.Error('ERR_STDOUT_CLOSE'); er = er || new ERR_STDOUT_CLOSE();
cb(er); cb(er);
}; };
if (stdout.isTTY) { if (stdout.isTTY) {
@ -30,7 +35,7 @@ function setupStdio() {
stderr.destroySoon = stderr.destroy; stderr.destroySoon = stderr.destroy;
stderr._destroy = function(er, cb) { stderr._destroy = function(er, cb) {
// Avoid errors if we already emitted // Avoid errors if we already emitted
er = er || new errors.Error('ERR_STDERR_CLOSE'); er = er || new ERR_STDERR_CLOSE();
cb(er); cb(er);
}; };
if (stderr.isTTY) { if (stderr.isTTY) {
@ -87,7 +92,7 @@ function setupStdio() {
default: default:
// Probably an error on in uv_guess_handle() // 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. // For supporting legacy API we put the FD here.
@ -171,7 +176,7 @@ function createWritableStdioStream(fd) {
default: default:
// Probably an error on in uv_guess_handle() // 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. // For supporting legacy API we put the FD here.

View File

@ -2,7 +2,7 @@
const config = process.binding('config'); const config = process.binding('config');
const prefix = `(${process.release.name}:${process.pid}) `; const prefix = `(${process.release.name}:${process.pid}) `;
const errors = require('internal/errors'); const { ERR_INVALID_ARG_TYPE } = require('internal/errors').codes;
exports.setup = setupProcessWarnings; exports.setup = setupProcessWarnings;
@ -122,9 +122,9 @@ function setupProcessWarnings() {
code = undefined; code = undefined;
} }
if (code !== undefined && typeof code !== 'string') 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') 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') { if (warning === undefined || typeof warning === 'string') {
warning = new Error(warning); warning = new Error(warning);
warning.name = String(type || 'Warning'); warning.name = String(type || 'Warning');
@ -133,8 +133,7 @@ function setupProcessWarnings() {
Error.captureStackTrace(warning, ctor || process.emitWarning); Error.captureStackTrace(warning, ctor || process.emitWarning);
} }
if (!(warning instanceof Error)) { if (!(warning instanceof Error)) {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('warning', ['Error', 'string']);
'warning', ['Error', 'string']);
} }
if (warning.name === 'DeprecationWarning') { if (warning.name === 'DeprecationWarning') {
if (process.noDeprecation) if (process.noDeprecation)

View File

@ -1,6 +1,6 @@
'use strict'; 'use strict';
const errors = require('internal/errors'); const { ERR_CHILD_CLOSED_BEFORE_REPLY } = require('internal/errors').codes;
const EventEmitter = require('events'); const EventEmitter = require('events');
@ -21,7 +21,7 @@ class SocketListSend extends EventEmitter {
function onclose() { function onclose() {
self.child.removeListener('internalMessage', onreply); self.child.removeListener('internalMessage', onreply);
callback(new errors.Error('ERR_CHILD_CLOSED_BEFORE_REPLY')); callback(new ERR_CHILD_CLOSED_BEFORE_REPLY());
} }
function onreply(msg) { function onreply(msg) {

View File

@ -1,18 +1,18 @@
'use strict'; 'use strict';
const errors = require('internal/errors'); const { ERR_INVALID_OPT_VALUE } = require('internal/errors').codes;
function getHighWaterMark(state, options, duplexKey, isDuplex) { function getHighWaterMark(state, options, duplexKey, isDuplex) {
let hwm = options.highWaterMark; let hwm = options.highWaterMark;
if (hwm != null) { if (hwm != null) {
if (typeof hwm !== 'number' || !(hwm >= 0)) 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); return Math.floor(hwm);
} else if (isDuplex) { } else if (isDuplex) {
hwm = options[duplexKey]; hwm = options[duplexKey];
if (hwm != null) { if (hwm != null) {
if (typeof hwm !== 'number' || !(hwm >= 0)) 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); return Math.floor(hwm);
} }
} }

View File

@ -10,7 +10,11 @@ const {
const async_id_symbol = Symbol('asyncId'); const async_id_symbol = Symbol('asyncId');
const trigger_async_id_symbol = Symbol('triggerId'); 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. // Timeout values > TIMEOUT_MAX are set to 1.
const TIMEOUT_MAX = 2 ** 31 - 1; const TIMEOUT_MAX = 2 ** 31 - 1;
@ -94,7 +98,7 @@ Timeout.prototype[refreshFnSymbol] = function refresh() {
function setUnrefTimeout(callback, after, arg1, arg2, arg3) { function setUnrefTimeout(callback, after, arg1, arg2, arg3) {
// Type checking identical to setTimeout() // Type checking identical to setTimeout()
if (typeof callback !== 'function') { if (typeof callback !== 'function') {
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
} }
let i, args; let i, args;
@ -127,13 +131,11 @@ function setUnrefTimeout(callback, after, arg1, arg2, arg3) {
// Type checking used by timers.enroll() and Socket#setTimeout() // Type checking used by timers.enroll() and Socket#setTimeout()
function validateTimerDuration(msecs) { function validateTimerDuration(msecs) {
if (typeof msecs !== 'number') { if (typeof msecs !== 'number') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', 'msecs', throw new ERR_INVALID_ARG_TYPE('msecs', 'number', msecs);
'number', msecs);
} }
if (msecs < 0 || !isFinite(msecs)) { if (msecs < 0 || !isFinite(msecs)) {
throw new errors.RangeError('ERR_OUT_OF_RANGE', 'msecs', throw new ERR_OUT_OF_RANGE('msecs', 'a non-negative finite number', msecs);
'a non-negative finite number', msecs);
} }
// Ensure that msecs fits into signed int32 // Ensure that msecs fits into signed int32

View File

@ -7,7 +7,18 @@ const {
} = require('internal/querystring'); } = require('internal/querystring');
const { getConstructorOf, removeColors } = require('internal/util'); 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 querystring = require('querystring');
const { platform } = process; const { platform } = process;
@ -107,7 +118,7 @@ class URLSearchParams {
this[searchParams] = childParams.slice(); this[searchParams] = childParams.slice();
} else if (method !== null && method !== undefined) { } else if (method !== null && method !== undefined) {
if (typeof method !== 'function') { if (typeof method !== 'function') {
throw new errors.TypeError('ERR_ARG_NOT_ITERABLE', 'Query pairs'); throw new ERR_ARG_NOT_ITERABLE('Query pairs');
} }
// sequence<sequence<USVString>> // sequence<sequence<USVString>>
@ -117,8 +128,7 @@ class URLSearchParams {
if ((typeof pair !== 'object' && typeof pair !== 'function') || if ((typeof pair !== 'object' && typeof pair !== 'function') ||
pair === null || pair === null ||
typeof pair[Symbol.iterator] !== 'function') { typeof pair[Symbol.iterator] !== 'function') {
throw new errors.TypeError('ERR_INVALID_TUPLE', 'Each query pair', throw new ERR_INVALID_TUPLE('Each query pair', '[name, value]');
'[name, value]');
} }
const convertedPair = []; const convertedPair = [];
for (const element of pair) for (const element of pair)
@ -129,8 +139,7 @@ class URLSearchParams {
this[searchParams] = []; this[searchParams] = [];
for (const pair of pairs) { for (const pair of pairs) {
if (pair.length !== 2) { if (pair.length !== 2) {
throw new errors.TypeError('ERR_INVALID_TUPLE', 'Each query pair', throw new ERR_INVALID_TUPLE('Each query pair', '[name, value]');
'[name, value]');
} }
this[searchParams].push(pair[0], pair[1]); this[searchParams].push(pair[0], pair[1]);
} }
@ -162,7 +171,7 @@ class URLSearchParams {
[util.inspect.custom](recurseTimes, ctx) { [util.inspect.custom](recurseTimes, ctx) {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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) if (typeof recurseTimes === 'number' && recurseTimes < 0)
@ -214,7 +223,7 @@ function onParseComplete(flags, protocol, username, password,
} }
function onParseError(flags, input) { function onParseError(flags, input) {
const error = new errors.TypeError('ERR_INVALID_URL', input); const error = new ERR_INVALID_URL(input);
error.input = input; error.input = input;
throw error; throw error;
} }
@ -328,7 +337,7 @@ class URL {
[util.inspect.custom](depth, opts) { [util.inspect.custom](depth, opts) {
if (this == null || if (this == null ||
Object.getPrototypeOf(this[context]) !== URLContext.prototype) { 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) if (typeof depth === 'number' && depth < 0)
@ -370,7 +379,7 @@ Object.defineProperties(URL.prototype, {
// eslint-disable-next-line func-name-matching // eslint-disable-next-line func-name-matching
value: function format(options) { value: function format(options) {
if (options && typeof options !== 'object') 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({ options = util._extend({
fragment: true, fragment: true,
unicode: false, unicode: false,
@ -943,10 +952,10 @@ function merge(out, start, mid, end, lBuffer, rBuffer) {
defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', { defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
append(name, value) { append(name, value) {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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) { if (arguments.length < 2) {
throw new errors.TypeError('ERR_MISSING_ARGS', 'name', 'value'); throw new ERR_MISSING_ARGS('name', 'value');
} }
name = toUSVString(name); name = toUSVString(name);
@ -957,10 +966,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
delete(name) { delete(name) {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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) { if (arguments.length < 1) {
throw new errors.TypeError('ERR_MISSING_ARGS', 'name'); throw new ERR_MISSING_ARGS('name');
} }
const list = this[searchParams]; const list = this[searchParams];
@ -978,10 +987,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
get(name) { get(name) {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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) { if (arguments.length < 1) {
throw new errors.TypeError('ERR_MISSING_ARGS', 'name'); throw new ERR_MISSING_ARGS('name');
} }
const list = this[searchParams]; const list = this[searchParams];
@ -996,10 +1005,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
getAll(name) { getAll(name) {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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) { if (arguments.length < 1) {
throw new errors.TypeError('ERR_MISSING_ARGS', 'name'); throw new ERR_MISSING_ARGS('name');
} }
const list = this[searchParams]; const list = this[searchParams];
@ -1015,10 +1024,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
has(name) { has(name) {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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) { if (arguments.length < 1) {
throw new errors.TypeError('ERR_MISSING_ARGS', 'name'); throw new ERR_MISSING_ARGS('name');
} }
const list = this[searchParams]; const list = this[searchParams];
@ -1033,10 +1042,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
set(name, value) { set(name, value) {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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) { if (arguments.length < 2) {
throw new errors.TypeError('ERR_MISSING_ARGS', 'name', 'value'); throw new ERR_MISSING_ARGS('name', 'value');
} }
const list = this[searchParams]; const list = this[searchParams];
@ -1120,7 +1129,7 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
// must be set to `entries`. // must be set to `entries`.
entries() { entries() {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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'); return createSearchParamsIterator(this, 'key+value');
@ -1128,10 +1137,10 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
forEach(callback, thisArg = undefined) { forEach(callback, thisArg = undefined) {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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') { if (typeof callback !== 'function') {
throw new errors.TypeError('ERR_INVALID_CALLBACK'); throw new ERR_INVALID_CALLBACK();
} }
let list = this[searchParams]; let list = this[searchParams];
@ -1150,7 +1159,7 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
// https://heycam.github.io/webidl/#es-iterable // https://heycam.github.io/webidl/#es-iterable
keys() { keys() {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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'); return createSearchParamsIterator(this, 'key');
@ -1158,7 +1167,7 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
values() { values() {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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'); return createSearchParamsIterator(this, 'value');
@ -1168,7 +1177,7 @@ defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
// https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior // https://url.spec.whatwg.org/#urlsearchparams-stringification-behavior
toString() { toString() {
if (!this || !this[searchParams] || this[searchParams][searchParams]) { 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]); return serializeParams(this[searchParams]);
@ -1200,7 +1209,7 @@ defineIDLClass(URLSearchParamsIteratorPrototype, 'URLSearchParams Iterator', {
next() { next() {
if (!this || if (!this ||
Object.getPrototypeOf(this) !== URLSearchParamsIteratorPrototype) { Object.getPrototypeOf(this) !== URLSearchParamsIteratorPrototype) {
throw new errors.TypeError('ERR_INVALID_THIS', 'URLSearchParamsIterator'); throw new ERR_INVALID_THIS('URLSearchParamsIterator');
} }
const { const {
@ -1237,7 +1246,7 @@ defineIDLClass(URLSearchParamsIteratorPrototype, 'URLSearchParams Iterator', {
}, },
[util.inspect.custom](recurseTimes, ctx) { [util.inspect.custom](recurseTimes, ctx) {
if (this == null || this[context] == null || this[context].target == null) 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) if (typeof recurseTimes === 'number' && recurseTimes < 0)
return ctx.stylize('[Object]', 'special'); return ctx.stylize('[Object]', 'special');
@ -1276,7 +1285,7 @@ defineIDLClass(URLSearchParamsIteratorPrototype, 'URLSearchParams Iterator', {
function domainToASCII(domain) { function domainToASCII(domain) {
if (arguments.length < 1) if (arguments.length < 1)
throw new errors.TypeError('ERR_MISSING_ARGS', 'domain'); throw new ERR_MISSING_ARGS('domain');
// toUSVString is not needed. // toUSVString is not needed.
return _domainToASCII(`${domain}`); return _domainToASCII(`${domain}`);
@ -1284,7 +1293,7 @@ function domainToASCII(domain) {
function domainToUnicode(domain) { function domainToUnicode(domain) {
if (arguments.length < 1) if (arguments.length < 1)
throw new errors.TypeError('ERR_MISSING_ARGS', 'domain'); throw new ERR_MISSING_ARGS('domain');
// toUSVString is not needed. // toUSVString is not needed.
return _domainToUnicode(`${domain}`); return _domainToUnicode(`${domain}`);
@ -1320,9 +1329,9 @@ function getPathFromURLWin32(url) {
var third = pathname.codePointAt(n + 2) | 0x20; var third = pathname.codePointAt(n + 2) | 0x20;
if ((pathname[n + 1] === '2' && third === 102) || // 2f 2F / if ((pathname[n + 1] === '2' && third === 102) || // 2f 2F /
(pathname[n + 1] === '5' && third === 99)) { // 5c 5C \ (pathname[n + 1] === '5' && third === 99)) { // 5c 5C \
throw new errors.TypeError( throw new ERR_INVALID_FILE_URL_PATH(
'ERR_INVALID_FILE_URL_PATH', 'must not include encoded \\ or / characters'
'must not include encoded \\ or / characters'); );
} }
} }
} }
@ -1341,8 +1350,7 @@ function getPathFromURLWin32(url) {
var sep = pathname[2]; var sep = pathname[2];
if (letter < 97 || letter > 122 || // a..z A..Z if (letter < 97 || letter > 122 || // a..z A..Z
(sep !== ':')) { (sep !== ':')) {
throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', throw new ERR_INVALID_FILE_URL_PATH('must be absolute');
'must be absolute');
} }
return pathname.slice(1); return pathname.slice(1);
} }
@ -1350,15 +1358,16 @@ function getPathFromURLWin32(url) {
function getPathFromURLPosix(url) { function getPathFromURLPosix(url) {
if (url.hostname !== '') { 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; var pathname = url.pathname;
for (var n = 0; n < pathname.length; n++) { for (var n = 0; n < pathname.length; n++) {
if (pathname[n] === '%') { if (pathname[n] === '%') {
var third = pathname.codePointAt(n + 2) | 0x20; var third = pathname.codePointAt(n + 2) | 0x20;
if (pathname[n + 1] === '2' && third === 102) { if (pathname[n + 1] === '2' && third === 102) {
throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', throw new ERR_INVALID_FILE_URL_PATH(
'must not include encoded / characters'); 'must not include encoded / characters'
);
} }
} }
} }
@ -1371,7 +1380,7 @@ function getPathFromURL(path) {
return path; return path;
} }
if (path.protocol !== 'file:') 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); return isWindows ? getPathFromURLWin32(path) : getPathFromURLPosix(path);
} }

View File

@ -1,6 +1,10 @@
'use strict'; '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 { signals } = process.binding('constants').os;
const { const {
@ -45,7 +49,7 @@ function deprecate(fn, msg, code) {
} }
if (code !== undefined && typeof code !== 'string') 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; let warned = false;
function deprecated(...args) { function deprecated(...args) {
@ -93,7 +97,7 @@ function decorateErrorStack(err) {
function assertCrypto() { function assertCrypto() {
if (noCrypto) if (noCrypto)
throw new errors.Error('ERR_NO_CRYPTO'); throw new ERR_NO_CRYPTO();
} }
// Return undefined if there is no match. // Return undefined if there is no match.
@ -225,7 +229,7 @@ function convertToValidSignal(signal) {
if (signalName) return signalName; if (signalName) return signalName;
} }
throw new errors.TypeError('ERR_UNKNOWN_SIGNAL', signal); throw new ERR_UNKNOWN_SIGNAL(signal);
} }
function getConstructorOf(obj) { function getConstructorOf(obj) {
@ -290,15 +294,12 @@ const kCustomPromisifyArgsSymbol = Symbol('customPromisifyArgs');
function promisify(original) { function promisify(original) {
if (typeof original !== 'function') 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]) { if (original[kCustomPromisifiedSymbol]) {
const fn = original[kCustomPromisifiedSymbol]; const fn = original[kCustomPromisifiedSymbol];
if (typeof fn !== 'function') { if (typeof fn !== 'function') {
throw new errors.TypeError('ERR_INVALID_ARG_TYPE', throw new ERR_INVALID_ARG_TYPE('util.promisify.custom', 'Function', fn);
'util.promisify.custom',
'Function',
fn);
} }
Object.defineProperty(fn, kCustomPromisifiedSymbol, { Object.defineProperty(fn, kCustomPromisifiedSymbol, {
value: fn, enumerable: false, writable: false, configurable: true value: fn, enumerable: false, writable: false, configurable: true

View File

@ -4,7 +4,15 @@ const { internalBinding } = require('internal/bootstrap_loaders');
const { emitExperimentalWarning } = require('internal/util'); const { emitExperimentalWarning } = require('internal/util');
const { URL } = require('internal/url'); const { URL } = require('internal/url');
const { kParsingContext, isContext } = process.binding('contextify'); 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 { const {
getConstructorOf, getConstructorOf,
customInspectSymbol, customInspectSymbol,
@ -41,27 +49,23 @@ class Module {
emitExperimentalWarning('vm.Module'); emitExperimentalWarning('vm.Module');
if (typeof src !== 'string') if (typeof src !== 'string')
throw new errors.TypeError( throw new ERR_INVALID_ARG_TYPE('src', 'string', src);
'ERR_INVALID_ARG_TYPE', 'src', 'string', src);
if (typeof options !== 'object' || options === null) if (typeof options !== 'object' || options === null)
throw new errors.TypeError( throw new ERR_INVALID_ARG_TYPE('options', 'object', options);
'ERR_INVALID_ARG_TYPE', 'options', 'object', options);
let context; let context;
if (options.context !== undefined) { if (options.context !== undefined) {
if (isContext(options.context)) { if (isContext(options.context)) {
context = options.context; context = options.context;
} else { } else {
throw new errors.TypeError( throw new ERR_INVALID_ARG_TYPE('options.context', 'vm.Context');
'ERR_INVALID_ARG_TYPE', 'options.context', 'vm.Context');
} }
} }
let url = options.url; let url = options.url;
if (url !== undefined) { if (url !== undefined) {
if (typeof url !== 'string') { if (typeof url !== 'string') {
throw new errors.TypeError( throw new ERR_INVALID_ARG_TYPE('options.url', 'string', url);
'ERR_INVALID_ARG_TYPE', 'options.url', 'string', url);
} }
url = new URL(url).href; url = new URL(url).href;
} else if (context === undefined) { } else if (context === undefined) {
@ -101,8 +105,9 @@ class Module {
get namespace() { get namespace() {
const wrap = wrapMap.get(this); const wrap = wrapMap.get(this);
if (wrap.getStatus() < kInstantiated) if (wrap.getStatus() < kInstantiated)
throw new errors.Error('ERR_VM_MODULE_STATUS', throw new ERR_VM_MODULE_STATUS(
'must not be uninstantiated or instantiating'); 'must not be uninstantiated or instantiating'
);
return wrap.namespace(); return wrap.namespace();
} }
@ -120,31 +125,30 @@ class Module {
get error() { get error() {
const wrap = wrapMap.get(this); const wrap = wrapMap.get(this);
if (wrap.getStatus() !== kErrored) 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(); return wrap.getError();
} }
async link(linker) { async link(linker) {
if (typeof linker !== 'function') if (typeof linker !== 'function')
throw new errors.TypeError( throw new ERR_INVALID_ARG_TYPE('linker', 'function', linker);
'ERR_INVALID_ARG_TYPE', 'linker', 'function', linker);
if (linkingStatusMap.get(this) !== 'unlinked') 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); const wrap = wrapMap.get(this);
if (wrap.getStatus() !== kUninstantiated) 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'); linkingStatusMap.set(this, 'linking');
const promises = wrap.link(async (specifier) => { const promises = wrap.link(async (specifier) => {
const m = await linker(specifier, this); const m = await linker(specifier, this);
if (!m || !wrapMap.has(m)) 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) 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); const childLinkingStatus = linkingStatusMap.get(m);
if (childLinkingStatus === 'errored') if (childLinkingStatus === 'errored')
throw new errors.Error('ERR_VM_MODULE_LINKING_ERRORED'); throw new ERR_VM_MODULE_LINKING_ERRORED();
if (childLinkingStatus === 'unlinked') if (childLinkingStatus === 'unlinked')
await m.link(linker); await m.link(linker);
return wrapMap.get(m); return wrapMap.get(m);
@ -164,10 +168,9 @@ class Module {
const wrap = wrapMap.get(this); const wrap = wrapMap.get(this);
const status = wrap.getStatus(); const status = wrap.getStatus();
if (status === kInstantiating || status === kEvaluating) if (status === kInstantiating || status === kEvaluating)
throw new errors.Error( throw new ERR_VM_MODULE_STATUS('must not be instantiating or evaluating');
'ERR_VM_MODULE_STATUS', 'must not be instantiating or evaluating');
if (linkingStatusMap.get(this) !== 'linked') if (linkingStatusMap.get(this) !== 'linked')
throw new errors.Error('ERR_VM_MODULE_NOT_LINKED'); throw new ERR_VM_MODULE_NOT_LINKED();
wrap.instantiate(); wrap.instantiate();
} }
@ -177,9 +180,9 @@ class Module {
if (status !== kInstantiated && if (status !== kInstantiated &&
status !== kEvaluated && status !== kEvaluated &&
status !== kErrored) { status !== kErrored) {
throw new errors.Error( throw new ERR_VM_MODULE_STATUS(
'ERR_VM_MODULE_STATUS', 'must be one of instantiated, evaluated, and errored'
'must be one of instantiated, evaluated, and errored'); );
} }
const result = wrap.evaluate(options); const result = wrap.evaluate(options);
return { result, __proto__: null }; return { result, __proto__: null };

View File

@ -6,7 +6,7 @@ const { Socket } = require('net');
const { JSStream } = process.binding('js_stream'); const { JSStream } = process.binding('js_stream');
const uv = process.binding('uv'); const uv = process.binding('uv');
const debug = util.debuglog('stream_wrap'); const debug = util.debuglog('stream_wrap');
const errors = require('internal/errors'); const { ERR_STREAM_WRAP } = require('internal/errors').codes;
const kCurrentWriteRequest = Symbol('kCurrentWriteRequest'); const kCurrentWriteRequest = Symbol('kCurrentWriteRequest');
const kCurrentShutdownRequest = Symbol('kCurrentShutdownRequest'); const kCurrentShutdownRequest = Symbol('kCurrentShutdownRequest');
@ -53,7 +53,7 @@ class JSStreamWrap extends Socket {
stream.pause(); stream.pause();
stream.removeListener('data', ondata); stream.removeListener('data', ondata);
this.emit('error', new errors.Error('ERR_STREAM_WRAP')); this.emit('error', new ERR_STREAM_WRAP());
return; return;
} }

View File

@ -6,13 +6,12 @@
const common = require('../common'); const common = require('../common');
const { search } = require('internal/loader/DefaultResolve'); const { search } = require('internal/loader/DefaultResolve');
const errors = require('internal/errors');
common.expectsError( common.expectsError(
() => search('target', undefined), () => search('target', undefined),
{ {
code: 'ERR_MISSING_MODULE', code: 'ERR_MISSING_MODULE',
type: errors.Error, type: Error,
message: 'Cannot find module target' message: 'Cannot find module target'
} }
); );

View File

@ -36,7 +36,7 @@ function check(async, sync) {
}, },
{ {
code: 'ERR_INVALID_ARG_VALUE', code: 'ERR_INVALID_ARG_VALUE',
type: Error, type: TypeError,
}); });
} }
@ -47,7 +47,7 @@ function check(async, sync) {
}, },
{ {
code: 'ERR_INVALID_ARG_VALUE', code: 'ERR_INVALID_ARG_VALUE',
type: Error type: TypeError
}); });
} }
} }

View File

@ -61,7 +61,7 @@ if (common.isWindows) {
}, },
{ {
code: 'ERR_INVALID_ARG_VALUE', code: 'ERR_INVALID_ARG_VALUE',
type: Error, type: TypeError,
message: 'The argument \'path\' must be a string or Uint8Array without ' + message: 'The argument \'path\' must be a string or Uint8Array without ' +
'null bytes. Received \'c:/tmp/\\u0000test\'' 'null bytes. Received \'c:/tmp/\\u0000test\''
} }
@ -95,7 +95,7 @@ if (common.isWindows) {
}, },
{ {
code: 'ERR_INVALID_ARG_VALUE', code: 'ERR_INVALID_ARG_VALUE',
type: Error, type: TypeError,
message: 'The argument \'path\' must be a string or Uint8Array without ' + message: 'The argument \'path\' must be a string or Uint8Array without ' +
'null bytes. Received \'/tmp/\\u0000test\'' 'null bytes. Received \'/tmp/\\u0000test\''
} }