Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[v9.x] backport 17338, 18186, 18358, 18546 #18916

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 21 additions & 1 deletion doc/api/util.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,25 @@ without any formatting.
util.format('%% %s'); // '%% %s'
```

## util.getSystemErrorName(err)
<!-- YAML
added: REPLACEME
-->

* `err` {number}
* Returns: {string}

Returns the string name for a numeric error code that comes from a Node.js API.
The mapping between error codes and error names is platform-dependent.
See [Common System Errors][] for the names of common errors.

```js
fs.access('file/that/does/not/exist', (err) => {
const name = util.getSystemErrorName(err.errno);
console.error(name); // ENOENT
});
```

## util.inherits(constructor, superConstructor)
<!-- YAML
added: v0.3.0
Expand Down Expand Up @@ -1228,5 +1247,6 @@ Deprecated predecessor of `console.log`.
[Customizing `util.inspect` colors]: #util_customizing_util_inspect_colors
[Internationalization]: intl.html
[WHATWG Encoding Standard]: https://encoding.spec.whatwg.org/
[constructor]: https://developer.mozilla.org/en-US/JavaScript/Reference/Global_Objects/Object/constructor
[Common System Errors]: errors.html#errors_common_system_errors
[constructor]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/constructor
[semantically incompatible]: https://github.com/nodejs/node/issues/4179
7 changes: 4 additions & 3 deletions lib/child_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,15 @@
'use strict';

const util = require('util');
const { deprecate, convertToValidSignal } = require('internal/util');
const {
deprecate, convertToValidSignal, getSystemErrorName
} = require('internal/util');
const { isUint8Array } = require('internal/util/types');
const { createPromise,
promiseResolve, promiseReject } = process.binding('util');
const debug = util.debuglog('child_process');
const { Buffer } = require('buffer');
const { Pipe, constants: PipeConstants } = process.binding('pipe_wrap');
const { errname } = process.binding('uv');
const child_process = require('internal/child_process');
const {
_validateStdio,
Expand Down Expand Up @@ -271,7 +272,7 @@ exports.execFile = function(file /*, args, options, callback*/) {
if (!ex) {
ex = new Error('Command failed: ' + cmd + '\n' + stderr);
ex.killed = child.killed || killed;
ex.code = code < 0 ? errname(code) : code;
ex.code = code < 0 ? getSystemErrorName(code) : code;
ex.signal = signal;
}

Expand Down
4 changes: 2 additions & 2 deletions lib/dgram.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ const SEND_BUFFER = false;
// Lazily loaded
var cluster = null;

const errnoException = util._errnoException;
const exceptionWithHostPort = util._exceptionWithHostPort;
const errnoException = errors.errnoException;
const exceptionWithHostPort = errors.exceptionWithHostPort;


function lookup4(lookup, address, callback) {
Expand Down
46 changes: 8 additions & 38 deletions lib/dns.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,10 @@

'use strict';

const util = require('util');

const cares = process.binding('cares_wrap');
const { isLegalPort } = require('internal/net');
const { customPromisifyArgs } = require('internal/util');
const errors = require('internal/errors');
const {
UV_EAI_MEMORY,
UV_EAI_NODATA,
UV_EAI_NONAME
} = process.binding('uv');

const {
GetAddrInfoReqWrap,
Expand All @@ -41,30 +34,6 @@ const {
isIP
} = cares;

function errnoException(err, syscall, hostname) {
// FIXME(bnoordhuis) Remove this backwards compatibility nonsense and pass
// the true error to the user. ENOTFOUND is not even a proper POSIX error!
if (err === UV_EAI_MEMORY ||
err === UV_EAI_NODATA ||
err === UV_EAI_NONAME) {
err = 'ENOTFOUND';
}
var ex = null;
if (typeof err === 'string') { // c-ares error code.
const errHost = hostname ? ` ${hostname}` : '';
ex = new Error(`${syscall} ${err}${errHost}`);
ex.code = err;
ex.errno = err;
ex.syscall = syscall;
} else {
ex = util._errnoException(err, syscall);
}
if (hostname) {
ex.hostname = hostname;
}
return ex;
}

const IANA_DNS_PORT = 53;
const digits = [
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0-15
Expand All @@ -91,10 +60,11 @@ function isIPv4(str) {
return (str.length > 3 && str.charCodeAt(3) === 46/*'.'*/);
}

const dnsException = errors.dnsException;

function onlookup(err, addresses) {
if (err) {
return this.callback(errnoException(err, 'getaddrinfo', this.hostname));
return this.callback(dnsException(err, 'getaddrinfo', this.hostname));
}
if (this.family) {
this.callback(null, addresses[0], this.family);
Expand All @@ -106,7 +76,7 @@ function onlookup(err, addresses) {

function onlookupall(err, addresses) {
if (err) {
return this.callback(errnoException(err, 'getaddrinfo', this.hostname));
return this.callback(dnsException(err, 'getaddrinfo', this.hostname));
}

var family = this.family;
Expand Down Expand Up @@ -186,7 +156,7 @@ function lookup(hostname, options, callback) {

var err = cares.getaddrinfo(req, hostname, family, hints, verbatim);
if (err) {
process.nextTick(callback, errnoException(err, 'getaddrinfo', hostname));
process.nextTick(callback, dnsException(err, 'getaddrinfo', hostname));
return {};
}
return req;
Expand All @@ -198,7 +168,7 @@ Object.defineProperty(lookup, customPromisifyArgs,

function onlookupservice(err, host, service) {
if (err)
return this.callback(errnoException(err, 'getnameinfo', this.host));
return this.callback(dnsException(err, 'getnameinfo', this.host));

this.callback(null, host, service);
}
Expand Down Expand Up @@ -227,7 +197,7 @@ function lookupService(host, port, callback) {
req.oncomplete = onlookupservice;

var err = cares.getnameinfo(req, host, port);
if (err) throw errnoException(err, 'getnameinfo', host);
if (err) throw dnsException(err, 'getnameinfo', host);
return req;
}

Expand All @@ -240,7 +210,7 @@ function onresolve(err, result, ttls) {
result = result.map((address, index) => ({ address, ttl: ttls[index] }));

if (err)
this.callback(errnoException(err, this.bindingName, this.hostname));
this.callback(dnsException(err, this.bindingName, this.hostname));
else
this.callback(null, result);
}
Expand Down Expand Up @@ -278,7 +248,7 @@ function resolver(bindingName) {
req.oncomplete = onresolve;
req.ttl = !!(options && options.ttl);
var err = this._handle[bindingName](req, name);
if (err) throw errnoException(err, bindingName);
if (err) throw dnsException(err, bindingName);
return req;
}
Object.defineProperty(query, 'name', { value: bindingName });
Expand Down
2 changes: 1 addition & 1 deletion lib/fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ const { kMaxLength } = require('buffer');
const isWindows = process.platform === 'win32';

const DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG);
const errnoException = util._errnoException;
const errnoException = errors.errnoException;

let truncateWarn = true;

Expand Down
2 changes: 1 addition & 1 deletion lib/internal/child_process.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ const {
UV_ESRCH
} = process.binding('uv');

const errnoException = util._errnoException;
const errnoException = errors.errnoException;
const { SocketListSend, SocketListReceive } = SocketList;

const MAX_HANDLE_RETRANSMISSIONS = 3;
Expand Down
138 changes: 133 additions & 5 deletions lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,30 @@
const kCode = Symbol('code');
const messages = new Map();

const {
UV_EAI_MEMORY,
UV_EAI_NODATA,
UV_EAI_NONAME
} = process.binding('uv');
const { kMaxLength } = process.binding('buffer');
const { defineProperty } = Object;

// Lazily loaded
var util = null;
var util_ = null;
function lazyUtil() {
if (!util_) {
util_ = require('util');
}
return util_;
}

var internalUtil = null;
function lazyInternalUtil() {
if (!internalUtil) {
internalUtil = require('internal/util');
}
return internalUtil;
}

function makeNodeError(Base) {
return class NodeError extends Base {
Expand Down Expand Up @@ -68,11 +87,11 @@ class AssertionError extends Error {
if (message) {
super(message);
} else {
const util = lazyUtil();
if (actual && actual.stack && actual instanceof Error)
actual = `${actual.name}: ${actual.message}`;
if (expected && expected.stack && expected instanceof Error)
expected = `${expected.name}: ${expected.message}`;
if (util === null) util = require('util');
super(`${util.inspect(actual).slice(0, 128)} ` +
`${operator} ${util.inspect(expected).slice(0, 128)}`);
}
Expand Down Expand Up @@ -107,7 +126,7 @@ function message(key, args) {
if (typeof msg === 'function') {
fmt = msg;
} else {
if (util === null) util = require('util');
const util = lazyUtil();
fmt = util.format;
if (args === undefined || args.length === 0)
return msg;
Expand All @@ -122,7 +141,110 @@ function E(sym, val) {
messages.set(sym, typeof val === 'function' ? val : String(val));
}

/**
* This used to be util._errnoException().
*
* @param {number} err - A libuv error number
* @param {string} syscall
* @param {string} [original]
* @returns {Error}
*/
function errnoException(err, syscall, original) {
// TODO(joyeecheung): We have to use the type-checked
// getSystemErrorName(err) to guard against invalid arguments from users.
// This can be replaced with [ code ] = errmap.get(err) when this method
// is no longer exposed to user land.
const code = lazyUtil().getSystemErrorName(err);
const message = original ?
`${syscall} ${code} ${original}` : `${syscall} ${code}`;

const ex = new Error(message);
// TODO(joyeecheung): errno is supposed to err, like in uvException
ex.code = ex.errno = code;
ex.syscall = syscall;

Error.captureStackTrace(ex, errnoException);
return ex;
}

/**
* This used to be util._exceptionWithHostPort().
*
* @param {number} err - A libuv error number
* @param {string} syscall
* @param {string} address
* @param {number} [port]
* @param {string} [additional]
* @returns {Error}
*/
function exceptionWithHostPort(err, syscall, address, port, additional) {
// TODO(joyeecheung): We have to use the type-checked
// getSystemErrorName(err) to guard against invalid arguments from users.
// This can be replaced with [ code ] = errmap.get(err) when this method
// is no longer exposed to user land.
const code = lazyUtil().getSystemErrorName(err);
let details = '';
if (port && port > 0) {
details = ` ${address}:${port}`;
} else if (address) {
details = ` ${address}`;
}
if (additional) {
details += ` - Local (${additional})`;
}

const ex = new Error(`${syscall} ${code}${details}`);
// TODO(joyeecheung): errno is supposed to err, like in uvException
ex.code = ex.errno = code;
ex.syscall = syscall;
ex.address = address;
if (port) {
ex.port = port;
}

Error.captureStackTrace(ex, exceptionWithHostPort);
return ex;
}

/**
* @param {number|string} err - A libuv error number or a c-ares error code
* @param {string} syscall
* @param {string} [hostname]
* @returns {Error}
*/
function dnsException(err, syscall, hostname) {
const ex = new Error();
// FIXME(bnoordhuis) Remove this backwards compatibility nonsense and pass
// the true error to the user. ENOTFOUND is not even a proper POSIX error!
if (err === UV_EAI_MEMORY ||
err === UV_EAI_NODATA ||
err === UV_EAI_NONAME) {
err = 'ENOTFOUND'; // Fabricated error name.
}
if (typeof err === 'string') { // c-ares error code.
const errHost = hostname ? ` ${hostname}` : '';
ex.message = `${syscall} ${err}${errHost}`;
// TODO(joyeecheung): errno is supposed to be a number, like in uvException
ex.code = ex.errno = err;
ex.syscall = syscall;
} else { // libuv error number
const code = lazyInternalUtil().getSystemErrorName(err);
ex.message = `${syscall} ${code}`;
// TODO(joyeecheung): errno is supposed to be err, like in uvException
ex.code = ex.errno = code;
ex.syscall = syscall;
}
if (hostname) {
ex.hostname = hostname;
}
Error.captureStackTrace(ex, dnsException);
return ex;
}

module.exports = exports = {
dnsException,
errnoException,
exceptionWithHostPort,
message,
Error: makeNodeError(Error),
TypeError: makeNodeError(TypeError),
Expand Down Expand Up @@ -263,8 +385,14 @@ E('ERR_INSPECTOR_CLOSED', 'Session was closed');
E('ERR_INSPECTOR_NOT_AVAILABLE', 'Inspector is not available');
E('ERR_INSPECTOR_NOT_CONNECTED', 'Session is not connected');
E('ERR_INVALID_ARG_TYPE', invalidArgType);
E('ERR_INVALID_ARG_VALUE', (name, value) =>
`The value "${String(value)}" is invalid for argument "${name}"`);
E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => {
const util = lazyUtil();
let inspected = util.inspect(value);
if (inspected.length > 128) {
inspected = inspected.slice(0, 128) + '...';
}
return `The argument '${name}' ${reason}. Received ${inspected}`;
}),
E('ERR_INVALID_ARRAY_LENGTH',
(name, len, actual) => {
internalAssert(typeof actual === 'number', 'actual must be a number');
Expand Down
Loading