• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/* eslint node-core/documented-errors: "error" */
2/* eslint node-core/alphabetize-errors: "error" */
3/* eslint node-core/prefer-util-format-errors: "error" */
4
5'use strict';
6
7// The whole point behind this internal module is to allow Node.js to no
8// longer be forced to treat every error message change as a semver-major
9// change. The NodeError classes here all expose a `code` property whose
10// value statically and permanently identifies the error. While the error
11// message may change, the code should not.
12
13const {
14  ArrayFrom,
15  ArrayIsArray,
16  ArrayPrototypeIncludes,
17  ArrayPrototypeIndexOf,
18  ArrayPrototypeJoin,
19  ArrayPrototypeMap,
20  ArrayPrototypePop,
21  ArrayPrototypePush,
22  ArrayPrototypeSlice,
23  ArrayPrototypeSplice,
24  ArrayPrototypeUnshift,
25  Error,
26  ErrorCaptureStackTrace,
27  ErrorPrototypeToString,
28  JSONStringify,
29  MapPrototypeGet,
30  MathAbs,
31  MathMax,
32  Number,
33  NumberIsInteger,
34  ObjectDefineProperty,
35  ObjectKeys,
36  RangeError,
37  ReflectApply,
38  RegExpPrototypeTest,
39  SafeMap,
40  SafeWeakMap,
41  String,
42  StringPrototypeEndsWith,
43  StringPrototypeIncludes,
44  StringPrototypeMatch,
45  StringPrototypeSlice,
46  StringPrototypeSplit,
47  StringPrototypeStartsWith,
48  StringPrototypeToLowerCase,
49  Symbol,
50  SymbolFor,
51  SyntaxError,
52  TypeError,
53  URIError,
54} = primordials;
55
56const isWindows = process.platform === 'win32';
57
58const messages = new SafeMap();
59const codes = {};
60
61const classRegExp = /^([A-Z][a-z0-9]*)+$/;
62// Sorted by a rough estimate on most frequently used entries.
63const kTypes = [
64  'string',
65  'function',
66  'number',
67  'object',
68  // Accept 'Function' and 'Object' as alternative to the lower cased version.
69  'Function',
70  'Object',
71  'boolean',
72  'bigint',
73  'symbol',
74];
75
76const MainContextError = Error;
77const overrideStackTrace = new SafeWeakMap();
78const kNoOverride = Symbol('kNoOverride');
79let userStackTraceLimit;
80const nodeInternalPrefix = '__node_internal_';
81const prepareStackTrace = (globalThis, error, trace) => {
82  // API for node internals to override error stack formatting
83  // without interfering with userland code.
84  if (overrideStackTrace.has(error)) {
85    const f = overrideStackTrace.get(error);
86    overrideStackTrace.delete(error);
87    return f(error, trace);
88  }
89
90  const firstFrame = trace[0]?.getFunctionName();
91  if (firstFrame && StringPrototypeStartsWith(firstFrame, nodeInternalPrefix)) {
92    for (let l = trace.length - 1; l >= 0; l--) {
93      const fn = trace[l]?.getFunctionName();
94      if (fn && StringPrototypeStartsWith(fn, nodeInternalPrefix)) {
95        ArrayPrototypeSplice(trace, 0, l + 1);
96        break;
97      }
98    }
99    // `userStackTraceLimit` is the user value for `Error.stackTraceLimit`,
100    // it is updated at every new exception in `captureLargerStackTrace`.
101    if (trace.length > userStackTraceLimit)
102      ArrayPrototypeSplice(trace, userStackTraceLimit);
103  }
104
105  const globalOverride =
106    maybeOverridePrepareStackTrace(globalThis, error, trace);
107  if (globalOverride !== kNoOverride) return globalOverride;
108
109  // Normal error formatting:
110  //
111  // Error: Message
112  //     at function (file)
113  //     at file
114  const errorString = ErrorPrototypeToString(error);
115  if (trace.length === 0) {
116    return errorString;
117  }
118  return `${errorString}\n    at ${ArrayPrototypeJoin(trace, '\n    at ')}`;
119};
120
121const maybeOverridePrepareStackTrace = (globalThis, error, trace) => {
122  // Polyfill of V8's Error.prepareStackTrace API.
123  // https://crbug.com/v8/7848
124  // `globalThis` is the global that contains the constructor which
125  // created `error`.
126  if (typeof globalThis.Error?.prepareStackTrace === 'function') {
127    return globalThis.Error.prepareStackTrace(error, trace);
128  }
129  // We still have legacy usage that depends on the main context's `Error`
130  // being used, even when the error is from a different context.
131  // TODO(devsnek): evaluate if this can be eventually deprecated/removed.
132  if (typeof MainContextError.prepareStackTrace === 'function') {
133    return MainContextError.prepareStackTrace(error, trace);
134  }
135
136  return kNoOverride;
137};
138
139// Lazily loaded
140let util;
141let assert;
142
143let internalUtil = null;
144function lazyInternalUtil() {
145  if (!internalUtil) {
146    internalUtil = require('internal/util');
147  }
148  return internalUtil;
149}
150
151let internalUtilInspect = null;
152function lazyInternalUtilInspect() {
153  if (!internalUtilInspect) {
154    internalUtilInspect = require('internal/util/inspect');
155  }
156  return internalUtilInspect;
157}
158
159let buffer;
160function lazyBuffer() {
161  if (buffer === undefined)
162    buffer = require('buffer').Buffer;
163  return buffer;
164}
165
166const addCodeToName = hideStackFrames(function addCodeToName(err, name, code) {
167  // Set the stack
168  err = captureLargerStackTrace(err);
169  // Add the error code to the name to include it in the stack trace.
170  err.name = `${name} [${code}]`;
171  // Access the stack to generate the error message including the error code
172  // from the name.
173  err.stack; // eslint-disable-line no-unused-expressions
174  // Reset the name to the actual name.
175  if (name === 'SystemError') {
176    ObjectDefineProperty(err, 'name', {
177      value: name,
178      enumerable: false,
179      writable: true,
180      configurable: true
181    });
182  } else {
183    delete err.name;
184  }
185});
186
187// A specialized Error that includes an additional info property with
188// additional information about the error condition.
189// It has the properties present in a UVException but with a custom error
190// message followed by the uv error code and uv error message.
191// It also has its own error code with the original uv error context put into
192// `err.info`.
193// The context passed into this error must have .code, .syscall and .message,
194// and may have .path and .dest.
195class SystemError extends Error {
196  constructor(key, context) {
197    const limit = Error.stackTraceLimit;
198    Error.stackTraceLimit = 0;
199    super();
200    // Reset the limit and setting the name property.
201    Error.stackTraceLimit = limit;
202    const prefix = getMessage(key, [], this);
203    let message = `${prefix}: ${context.syscall} returned ` +
204                  `${context.code} (${context.message})`;
205
206    if (context.path !== undefined)
207      message += ` ${context.path}`;
208    if (context.dest !== undefined)
209      message += ` => ${context.dest}`;
210
211    ObjectDefineProperty(this, 'message', {
212      value: message,
213      enumerable: false,
214      writable: true,
215      configurable: true
216    });
217    addCodeToName(this, 'SystemError', key);
218
219    this.code = key;
220
221    ObjectDefineProperty(this, 'info', {
222      value: context,
223      enumerable: true,
224      configurable: true,
225      writable: false
226    });
227
228    ObjectDefineProperty(this, 'errno', {
229      get() {
230        return context.errno;
231      },
232      set: (value) => {
233        context.errno = value;
234      },
235      enumerable: true,
236      configurable: true
237    });
238
239    ObjectDefineProperty(this, 'syscall', {
240      get() {
241        return context.syscall;
242      },
243      set: (value) => {
244        context.syscall = value;
245      },
246      enumerable: true,
247      configurable: true
248    });
249
250    if (context.path !== undefined) {
251      // TODO(BridgeAR): Investigate why and when the `.toString()` was
252      // introduced. The `path` and `dest` properties in the context seem to
253      // always be of type string. We should probably just remove the
254      // `.toString()` and `Buffer.from()` operations and set the value on the
255      // context as the user did.
256      ObjectDefineProperty(this, 'path', {
257        get() {
258          return context.path != null ?
259            context.path.toString() : context.path;
260        },
261        set: (value) => {
262          context.path = value ?
263            lazyBuffer().from(value.toString()) : undefined;
264        },
265        enumerable: true,
266        configurable: true
267      });
268    }
269
270    if (context.dest !== undefined) {
271      ObjectDefineProperty(this, 'dest', {
272        get() {
273          return context.dest != null ?
274            context.dest.toString() : context.dest;
275        },
276        set: (value) => {
277          context.dest = value ?
278            lazyBuffer().from(value.toString()) : undefined;
279        },
280        enumerable: true,
281        configurable: true
282      });
283    }
284  }
285
286  toString() {
287    return `${this.name} [${this.code}]: ${this.message}`;
288  }
289
290  [SymbolFor('nodejs.util.inspect.custom')](recurseTimes, ctx) {
291    return lazyInternalUtilInspect().inspect(this, {
292      ...ctx,
293      getters: true,
294      customInspect: false
295    });
296  }
297}
298
299function makeSystemErrorWithCode(key) {
300  return class NodeError extends SystemError {
301    constructor(ctx) {
302      super(key, ctx);
303    }
304  };
305}
306
307function makeNodeErrorWithCode(Base, key) {
308  return class NodeError extends Base {
309    constructor(...args) {
310      const limit = Error.stackTraceLimit;
311      Error.stackTraceLimit = 0;
312      super();
313      // Reset the limit and setting the name property.
314      Error.stackTraceLimit = limit;
315      const message = getMessage(key, args, this);
316      ObjectDefineProperty(this, 'message', {
317        value: message,
318        enumerable: false,
319        writable: true,
320        configurable: true
321      });
322      addCodeToName(this, super.name, key);
323      this.code = key;
324    }
325
326    toString() {
327      return `${this.name} [${key}]: ${this.message}`;
328    }
329  };
330}
331
332// This function removes unnecessary frames from Node.js core errors.
333function hideStackFrames(fn) {
334  // We rename the functions that will be hidden to cut off the stacktrace
335  // at the outermost one
336  const hidden = nodeInternalPrefix + fn.name;
337  ObjectDefineProperty(fn, 'name', { value: hidden });
338  return fn;
339}
340
341// Utility function for registering the error codes. Only used here. Exported
342// *only* to allow for testing.
343function E(sym, val, def, ...otherClasses) {
344  // Special case for SystemError that formats the error message differently
345  // The SystemErrors only have SystemError as their base classes.
346  messages.set(sym, val);
347  if (def === SystemError) {
348    def = makeSystemErrorWithCode(sym);
349  } else {
350    def = makeNodeErrorWithCode(def, sym);
351  }
352
353  if (otherClasses.length !== 0) {
354    otherClasses.forEach((clazz) => {
355      def[clazz.name] = makeNodeErrorWithCode(clazz, sym);
356    });
357  }
358  codes[sym] = def;
359}
360
361function getMessage(key, args, self) {
362  const msg = messages.get(key);
363
364  if (assert === undefined) assert = require('internal/assert');
365
366  if (typeof msg === 'function') {
367    assert(
368      msg.length <= args.length, // Default options do not count.
369      `Code: ${key}; The provided arguments length (${args.length}) does not ` +
370        `match the required ones (${msg.length}).`
371    );
372    return ReflectApply(msg, self, args);
373  }
374
375  const expectedLength =
376    (StringPrototypeMatch(msg, /%[dfijoOs]/g) || []).length;
377  assert(
378    expectedLength === args.length,
379    `Code: ${key}; The provided arguments length (${args.length}) does not ` +
380      `match the required ones (${expectedLength}).`
381  );
382  if (args.length === 0)
383    return msg;
384
385  ArrayPrototypeUnshift(args, msg);
386  return ReflectApply(lazyInternalUtilInspect().format, null, args);
387}
388
389let uvBinding;
390
391function lazyUv() {
392  if (!uvBinding) {
393    uvBinding = internalBinding('uv');
394  }
395  return uvBinding;
396}
397
398const uvUnmappedError = ['UNKNOWN', 'unknown error'];
399
400function uvErrmapGet(name) {
401  uvBinding = lazyUv();
402  if (!uvBinding.errmap) {
403    uvBinding.errmap = uvBinding.getErrorMap();
404  }
405  return MapPrototypeGet(uvBinding.errmap, name);
406}
407
408const captureLargerStackTrace = hideStackFrames(
409  function captureLargerStackTrace(err) {
410    userStackTraceLimit = Error.stackTraceLimit;
411    Error.stackTraceLimit = Infinity;
412    ErrorCaptureStackTrace(err);
413    // Reset the limit
414    Error.stackTraceLimit = userStackTraceLimit;
415
416    return err;
417  });
418
419/**
420 * This creates an error compatible with errors produced in the C++
421 * function UVException using a context object with data assembled in C++.
422 * The goal is to migrate them to ERR_* errors later when compatibility is
423 * not a concern.
424 *
425 * @param {Object} ctx
426 * @returns {Error}
427 */
428const uvException = hideStackFrames(function uvException(ctx) {
429  const { 0: code, 1: uvmsg } = uvErrmapGet(ctx.errno) || uvUnmappedError;
430  let message = `${code}: ${ctx.message || uvmsg}, ${ctx.syscall}`;
431
432  let path;
433  let dest;
434  if (ctx.path) {
435    path = ctx.path.toString();
436    message += ` '${path}'`;
437  }
438  if (ctx.dest) {
439    dest = ctx.dest.toString();
440    message += ` -> '${dest}'`;
441  }
442
443  // Reducing the limit improves the performance significantly. We do not lose
444  // the stack frames due to the `captureStackTrace()` function that is called
445  // later.
446  const tmpLimit = Error.stackTraceLimit;
447  Error.stackTraceLimit = 0;
448  // Pass the message to the constructor instead of setting it on the object
449  // to make sure it is the same as the one created in C++
450  // eslint-disable-next-line no-restricted-syntax
451  const err = new Error(message);
452  Error.stackTraceLimit = tmpLimit;
453
454  for (const prop of ObjectKeys(ctx)) {
455    if (prop === 'message' || prop === 'path' || prop === 'dest') {
456      continue;
457    }
458    err[prop] = ctx[prop];
459  }
460
461  err.code = code;
462  if (path) {
463    err.path = path;
464  }
465  if (dest) {
466    err.dest = dest;
467  }
468
469  return captureLargerStackTrace(err);
470});
471
472/**
473 * This creates an error compatible with errors produced in the C++
474 * This function should replace the deprecated
475 * `exceptionWithHostPort()` function.
476 *
477 * @param {number} err - A libuv error number
478 * @param {string} syscall
479 * @param {string} address
480 * @param {number} [port]
481 * @returns {Error}
482 */
483const uvExceptionWithHostPort = hideStackFrames(
484  function uvExceptionWithHostPort(err, syscall, address, port) {
485    const { 0: code, 1: uvmsg } = uvErrmapGet(err) || uvUnmappedError;
486    const message = `${syscall} ${code}: ${uvmsg}`;
487    let details = '';
488
489    if (port && port > 0) {
490      details = ` ${address}:${port}`;
491    } else if (address) {
492      details = ` ${address}`;
493    }
494
495    // Reducing the limit improves the performance significantly. We do not
496    // lose the stack frames due to the `captureStackTrace()` function that
497    // is called later.
498    const tmpLimit = Error.stackTraceLimit;
499    Error.stackTraceLimit = 0;
500    // eslint-disable-next-line no-restricted-syntax
501    const ex = new Error(`${message}${details}`);
502    Error.stackTraceLimit = tmpLimit;
503    ex.code = code;
504    ex.errno = err;
505    ex.syscall = syscall;
506    ex.address = address;
507    if (port) {
508      ex.port = port;
509    }
510
511    return captureLargerStackTrace(ex);
512  });
513
514/**
515 * This used to be util._errnoException().
516 *
517 * @param {number} err - A libuv error number
518 * @param {string} syscall
519 * @param {string} [original]
520 * @returns {Error}
521 */
522const errnoException = hideStackFrames(
523  function errnoException(err, syscall, original) {
524    // TODO(joyeecheung): We have to use the type-checked
525    // getSystemErrorName(err) to guard against invalid arguments from users.
526    // This can be replaced with [ code ] = errmap.get(err) when this method
527    // is no longer exposed to user land.
528    if (util === undefined) util = require('util');
529    const code = util.getSystemErrorName(err);
530    const message = original ?
531      `${syscall} ${code} ${original}` : `${syscall} ${code}`;
532
533    const tmpLimit = Error.stackTraceLimit;
534    Error.stackTraceLimit = 0;
535    // eslint-disable-next-line no-restricted-syntax
536    const ex = new Error(message);
537    Error.stackTraceLimit = tmpLimit;
538    ex.errno = err;
539    ex.code = code;
540    ex.syscall = syscall;
541
542    return captureLargerStackTrace(ex);
543  });
544
545/**
546 * Deprecated, new function is `uvExceptionWithHostPort()`
547 * New function added the error description directly
548 * from C++. this method for backwards compatibility
549 * @param {number} err - A libuv error number
550 * @param {string} syscall
551 * @param {string} address
552 * @param {number} [port]
553 * @param {string} [additional]
554 * @returns {Error}
555 */
556const exceptionWithHostPort = hideStackFrames(
557  function exceptionWithHostPort(err, syscall, address, port, additional) {
558    // TODO(joyeecheung): We have to use the type-checked
559    // getSystemErrorName(err) to guard against invalid arguments from users.
560    // This can be replaced with [ code ] = errmap.get(err) when this method
561    // is no longer exposed to user land.
562    if (util === undefined) util = require('util');
563    const code = util.getSystemErrorName(err);
564    let details = '';
565    if (port && port > 0) {
566      details = ` ${address}:${port}`;
567    } else if (address) {
568      details = ` ${address}`;
569    }
570    if (additional) {
571      details += ` - Local (${additional})`;
572    }
573
574    // Reducing the limit improves the performance significantly. We do not
575    // lose the stack frames due to the `captureStackTrace()` function that
576    // is called later.
577    const tmpLimit = Error.stackTraceLimit;
578    Error.stackTraceLimit = 0;
579    // eslint-disable-next-line no-restricted-syntax
580    const ex = new Error(`${syscall} ${code}${details}`);
581    Error.stackTraceLimit = tmpLimit;
582    ex.errno = err;
583    ex.code = code;
584    ex.syscall = syscall;
585    ex.address = address;
586    if (port) {
587      ex.port = port;
588    }
589
590    return captureLargerStackTrace(ex);
591  });
592
593/**
594 * @param {number|string} code - A libuv error number or a c-ares error code
595 * @param {string} syscall
596 * @param {string} [hostname]
597 * @returns {Error}
598 */
599const dnsException = hideStackFrames(function(code, syscall, hostname) {
600  let errno;
601  // If `code` is of type number, it is a libuv error number, else it is a
602  // c-ares error code.
603  // TODO(joyeecheung): translate c-ares error codes into numeric ones and
604  // make them available in a property that's not error.errno (since they
605  // can be in conflict with libuv error codes). Also make sure
606  // util.getSystemErrorName() can understand them when an being informed that
607  // the number is a c-ares error code.
608  if (typeof code === 'number') {
609    errno = code;
610    // ENOTFOUND is not a proper POSIX error, but this error has been in place
611    // long enough that it's not practical to remove it.
612    if (code === lazyUv().UV_EAI_NODATA || code === lazyUv().UV_EAI_NONAME) {
613      code = 'ENOTFOUND'; // Fabricated error name.
614    } else {
615      code = lazyInternalUtil().getSystemErrorName(code);
616    }
617  }
618  const message = `${syscall} ${code}${hostname ? ` ${hostname}` : ''}`;
619  // Reducing the limit improves the performance significantly. We do not lose
620  // the stack frames due to the `captureStackTrace()` function that is called
621  // later.
622  const tmpLimit = Error.stackTraceLimit;
623  Error.stackTraceLimit = 0;
624  // eslint-disable-next-line no-restricted-syntax
625  const ex = new Error(message);
626  Error.stackTraceLimit = tmpLimit;
627  ex.errno = errno;
628  ex.code = code;
629  ex.syscall = syscall;
630  if (hostname) {
631    ex.hostname = hostname;
632  }
633
634  return captureLargerStackTrace(ex);
635});
636
637function connResetException(msg) {
638  // eslint-disable-next-line no-restricted-syntax
639  const ex = new Error(msg);
640  ex.code = 'ECONNRESET';
641  return ex;
642}
643
644let maxStack_ErrorName;
645let maxStack_ErrorMessage;
646/**
647 * Returns true if `err.name` and `err.message` are equal to engine-specific
648 * values indicating max call stack size has been exceeded.
649 * "Maximum call stack size exceeded" in V8.
650 *
651 * @param {Error} err
652 * @returns {boolean}
653 */
654function isStackOverflowError(err) {
655  if (maxStack_ErrorMessage === undefined) {
656    try {
657      function overflowStack() { overflowStack(); }
658      overflowStack();
659    } catch (err) {
660      maxStack_ErrorMessage = err.message;
661      maxStack_ErrorName = err.name;
662    }
663  }
664
665  return err && err.name === maxStack_ErrorName &&
666         err.message === maxStack_ErrorMessage;
667}
668
669// Only use this for integers! Decimal numbers do not work with this function.
670function addNumericalSeparator(val) {
671  let res = '';
672  let i = val.length;
673  const start = val[0] === '-' ? 1 : 0;
674  for (; i >= start + 4; i -= 3) {
675    res = `_${StringPrototypeSlice(val, i - 3, i)}${res}`;
676  }
677  return `${StringPrototypeSlice(val, 0, i)}${res}`;
678}
679
680// Used to enhance the stack that will be picked up by the inspector
681const kEnhanceStackBeforeInspector = Symbol('kEnhanceStackBeforeInspector');
682
683// These are supposed to be called only on fatal exceptions before
684// the process exits.
685const fatalExceptionStackEnhancers = {
686  beforeInspector(error) {
687    if (typeof error[kEnhanceStackBeforeInspector] !== 'function') {
688      return error.stack;
689    }
690
691    try {
692      // Set the error.stack here so it gets picked up by the
693      // inspector.
694      error.stack = error[kEnhanceStackBeforeInspector]();
695    } catch {
696      // We are just enhancing the error. If it fails, ignore it.
697    }
698    return error.stack;
699  },
700  afterInspector(error) {
701    const originalStack = error.stack;
702    let useColors = true;
703    // Some consoles do not convert ANSI escape sequences to colors,
704    // rather display them directly to the stdout. On those consoles,
705    // libuv emulates colors by intercepting stdout stream and calling
706    // corresponding Windows API functions for setting console colors.
707    // However, fatal error are handled differently and we cannot easily
708    // highlight them. On Windows, detecting whether a console supports
709    // ANSI escape sequences is not reliable.
710    if (process.platform === 'win32') {
711      const info = internalBinding('os').getOSInformation();
712      const ver = ArrayPrototypeMap(StringPrototypeSplit(info[2], '.'),
713                                    Number);
714      if (ver[0] !== 10 || ver[2] < 14393) {
715        useColors = false;
716      }
717    }
718    const {
719      inspect,
720      inspectDefaultOptions: {
721        colors: defaultColors
722      }
723    } = lazyInternalUtilInspect();
724    const colors = useColors &&
725                   ((internalBinding('util').guessHandleType(2) === 'TTY' &&
726                   require('internal/tty').hasColors()) ||
727                   defaultColors);
728    try {
729      return inspect(error, {
730        colors,
731        customInspect: false,
732        depth: MathMax(inspect.defaultOptions.depth, 5)
733      });
734    } catch {
735      return originalStack;
736    }
737  }
738};
739
740// Node uses an AbortError that isn't exactly the same as the DOMException
741// to make usage of the error in userland and readable-stream easier.
742// It is a regular error with `.code` and `.name`.
743class AbortError extends Error {
744  constructor() {
745    super('The operation was aborted');
746    this.code = 'ABORT_ERR';
747    this.name = 'AbortError';
748  }
749}
750module.exports = {
751  addCodeToName, // Exported for NghttpError
752  codes,
753  dnsException,
754  errnoException,
755  exceptionWithHostPort,
756  getMessage,
757  hideStackFrames,
758  isStackOverflowError,
759  connResetException,
760  uvErrmapGet,
761  uvException,
762  uvExceptionWithHostPort,
763  SystemError,
764  AbortError,
765  // This is exported only to facilitate testing.
766  E,
767  kNoOverride,
768  prepareStackTrace,
769  maybeOverridePrepareStackTrace,
770  overrideStackTrace,
771  kEnhanceStackBeforeInspector,
772  fatalExceptionStackEnhancers
773};
774
775// To declare an error message, use the E(sym, val, def) function above. The sym
776// must be an upper case string. The val can be either a function or a string.
777// The def must be an error class.
778// The return value of the function must be a string.
779// Examples:
780// E('EXAMPLE_KEY1', 'This is the error value', Error);
781// E('EXAMPLE_KEY2', (a, b) => return `${a} ${b}`, RangeError);
782//
783// Once an error code has been assigned, the code itself MUST NOT change and
784// any given error code must never be reused to identify a different error.
785//
786// Any error code added here should also be added to the documentation
787//
788// Note: Please try to keep these in alphabetical order
789//
790// Note: Node.js specific errors must begin with the prefix ERR_
791E('ERR_AMBIGUOUS_ARGUMENT', 'The "%s" argument is ambiguous. %s', TypeError);
792E('ERR_ARG_NOT_ITERABLE', '%s must be iterable', TypeError);
793E('ERR_ASSERTION', '%s', Error);
794E('ERR_ASYNC_CALLBACK', '%s must be a function', TypeError);
795E('ERR_ASYNC_TYPE', 'Invalid name for async "type": %s', TypeError);
796E('ERR_BROTLI_INVALID_PARAM', '%s is not a valid Brotli parameter', RangeError);
797E('ERR_BUFFER_OUT_OF_BOUNDS',
798  // Using a default argument here is important so the argument is not counted
799  // towards `Function#length`.
800  (name = undefined) => {
801    if (name) {
802      return `"${name}" is outside of buffer bounds`;
803    }
804    return 'Attempt to access memory outside buffer bounds';
805  }, RangeError);
806E('ERR_BUFFER_TOO_LARGE',
807  'Cannot create a Buffer larger than %s bytes',
808  RangeError);
809E('ERR_CANNOT_WATCH_SIGINT', 'Cannot watch for SIGINT signals', Error);
810E('ERR_CHILD_CLOSED_BEFORE_REPLY',
811  'Child closed before reply received', Error);
812E('ERR_CHILD_PROCESS_IPC_REQUIRED',
813  "Forked processes must have an IPC channel, missing value 'ipc' in %s",
814  Error);
815E('ERR_CHILD_PROCESS_STDIO_MAXBUFFER', '%s maxBuffer length exceeded',
816  RangeError);
817E('ERR_CONSOLE_WRITABLE_STREAM',
818  'Console expects a writable stream instance for %s', TypeError);
819E('ERR_CONTEXT_NOT_INITIALIZED', 'context used is not initialized', Error);
820E('ERR_CPU_USAGE', 'Unable to obtain cpu usage %s', Error);
821E('ERR_CRYPTO_CUSTOM_ENGINE_NOT_SUPPORTED',
822  'Custom engines not supported by this OpenSSL', Error);
823E('ERR_CRYPTO_ECDH_INVALID_FORMAT', 'Invalid ECDH format: %s', TypeError);
824E('ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY',
825  'Public key is not valid for specified curve', Error);
826E('ERR_CRYPTO_ENGINE_UNKNOWN', 'Engine "%s" was not found', Error);
827E('ERR_CRYPTO_FIPS_FORCED',
828  'Cannot set FIPS mode, it was forced with --force-fips at startup.', Error);
829E('ERR_CRYPTO_FIPS_UNAVAILABLE', 'Cannot set FIPS mode in a non-FIPS build.',
830  Error);
831E('ERR_CRYPTO_HASH_FINALIZED', 'Digest already called', Error);
832E('ERR_CRYPTO_HASH_UPDATE_FAILED', 'Hash update failed', Error);
833E('ERR_CRYPTO_INCOMPATIBLE_KEY', 'Incompatible %s: %s', Error);
834E('ERR_CRYPTO_INCOMPATIBLE_KEY_OPTIONS', 'The selected key encoding %s %s.',
835  Error);
836E('ERR_CRYPTO_INVALID_DIGEST', 'Invalid digest: %s', TypeError);
837E('ERR_CRYPTO_INVALID_KEY_OBJECT_TYPE',
838  'Invalid key object type %s, expected %s.', TypeError);
839E('ERR_CRYPTO_INVALID_STATE', 'Invalid state for operation %s', Error);
840E('ERR_CRYPTO_PBKDF2_ERROR', 'PBKDF2 error', Error);
841E('ERR_CRYPTO_SCRYPT_INVALID_PARAMETER', 'Invalid scrypt parameter', Error);
842E('ERR_CRYPTO_SCRYPT_NOT_SUPPORTED', 'Scrypt algorithm not supported', Error);
843// Switch to TypeError. The current implementation does not seem right.
844E('ERR_CRYPTO_SIGN_KEY_REQUIRED', 'No key provided to sign', Error);
845E('ERR_DEBUGGER_ERROR', '%s', Error);
846E('ERR_DEBUGGER_STARTUP_ERROR', '%s', Error);
847E('ERR_DIR_CLOSED', 'Directory handle was closed', Error);
848E('ERR_DIR_CONCURRENT_OPERATION',
849  'Cannot do synchronous work on directory handle with concurrent ' +
850  'asynchronous operations', Error);
851E('ERR_DNS_SET_SERVERS_FAILED', 'c-ares failed to set servers: "%s" [%s]',
852  Error);
853E('ERR_DOMAIN_CALLBACK_NOT_AVAILABLE',
854  'A callback was registered through ' +
855     'process.setUncaughtExceptionCaptureCallback(), which is mutually ' +
856     'exclusive with using the `domain` module',
857  Error);
858E('ERR_DOMAIN_CANNOT_SET_UNCAUGHT_EXCEPTION_CAPTURE',
859  'The `domain` module is in use, which is mutually exclusive with calling ' +
860     'process.setUncaughtExceptionCaptureCallback()',
861  Error);
862E('ERR_ENCODING_INVALID_ENCODED_DATA', function(encoding, ret) {
863  this.errno = ret;
864  return `The encoded data was not valid for encoding ${encoding}`;
865}, TypeError);
866E('ERR_ENCODING_NOT_SUPPORTED', 'The "%s" encoding is not supported',
867  RangeError);
868E('ERR_EVAL_ESM_CANNOT_PRINT', '--print cannot be used with ESM input', Error);
869E('ERR_EVENT_RECURSION', 'The event "%s" is already being dispatched', Error);
870E('ERR_FALSY_VALUE_REJECTION', function(reason) {
871  this.reason = reason;
872  return 'Promise was rejected with falsy value';
873}, Error);
874E('ERR_FEATURE_UNAVAILABLE_ON_PLATFORM',
875  'The feature %s is unavailable on the current platform' +
876  ', which is being used to run Node.js',
877  TypeError);
878E('ERR_FS_EISDIR', 'Path is a directory', SystemError);
879E('ERR_FS_FILE_TOO_LARGE', 'File size (%s) is greater than 2 GB', RangeError);
880E('ERR_FS_INVALID_SYMLINK_TYPE',
881  'Symlink type must be one of "dir", "file", or "junction". Received "%s"',
882  Error); // Switch to TypeError. The current implementation does not seem right
883E('ERR_HTTP2_ALTSVC_INVALID_ORIGIN',
884  'HTTP/2 ALTSVC frames require a valid origin', TypeError);
885E('ERR_HTTP2_ALTSVC_LENGTH',
886  'HTTP/2 ALTSVC frames are limited to 16382 bytes', TypeError);
887E('ERR_HTTP2_CONNECT_AUTHORITY',
888  ':authority header is required for CONNECT requests', Error);
889E('ERR_HTTP2_CONNECT_PATH',
890  'The :path header is forbidden for CONNECT requests', Error);
891E('ERR_HTTP2_CONNECT_SCHEME',
892  'The :scheme header is forbidden for CONNECT requests', Error);
893E('ERR_HTTP2_GOAWAY_SESSION',
894  'New streams cannot be created after receiving a GOAWAY', Error);
895E('ERR_HTTP2_HEADERS_AFTER_RESPOND',
896  'Cannot specify additional headers after response initiated', Error);
897E('ERR_HTTP2_HEADERS_SENT', 'Response has already been initiated.', Error);
898E('ERR_HTTP2_HEADER_SINGLE_VALUE',
899  'Header field "%s" must only have a single value', TypeError);
900E('ERR_HTTP2_INFO_STATUS_NOT_ALLOWED',
901  'Informational status codes cannot be used', RangeError);
902E('ERR_HTTP2_INVALID_CONNECTION_HEADERS',
903  'HTTP/1 Connection specific headers are forbidden: "%s"', TypeError);
904E('ERR_HTTP2_INVALID_HEADER_VALUE',
905  'Invalid value "%s" for header "%s"', TypeError);
906E('ERR_HTTP2_INVALID_INFO_STATUS',
907  'Invalid informational status code: %s', RangeError);
908E('ERR_HTTP2_INVALID_ORIGIN',
909  'HTTP/2 ORIGIN frames require a valid origin', TypeError);
910E('ERR_HTTP2_INVALID_PACKED_SETTINGS_LENGTH',
911  'Packed settings length must be a multiple of six', RangeError);
912E('ERR_HTTP2_INVALID_PSEUDOHEADER',
913  '"%s" is an invalid pseudoheader or is used incorrectly', TypeError);
914E('ERR_HTTP2_INVALID_SESSION', 'The session has been destroyed', Error);
915E('ERR_HTTP2_INVALID_SETTING_VALUE',
916  // Using default arguments here is important so the arguments are not counted
917  // towards `Function#length`.
918  function(name, actual, min = undefined, max = undefined) {
919    this.actual = actual;
920    if (min !== undefined) {
921      this.min = min;
922      this.max = max;
923    }
924    return `Invalid value for setting "${name}": ${actual}`;
925  }, TypeError, RangeError);
926E('ERR_HTTP2_INVALID_STREAM', 'The stream has been destroyed', Error);
927E('ERR_HTTP2_MAX_PENDING_SETTINGS_ACK',
928  'Maximum number of pending settings acknowledgements', Error);
929E('ERR_HTTP2_NESTED_PUSH',
930  'A push stream cannot initiate another push stream.', Error);
931E('ERR_HTTP2_NO_MEM', 'Out of memory', Error);
932E('ERR_HTTP2_NO_SOCKET_MANIPULATION',
933  'HTTP/2 sockets should not be directly manipulated (e.g. read and written)',
934  Error);
935E('ERR_HTTP2_ORIGIN_LENGTH',
936  'HTTP/2 ORIGIN frames are limited to 16382 bytes', TypeError);
937E('ERR_HTTP2_OUT_OF_STREAMS',
938  'No stream ID is available because maximum stream ID has been reached',
939  Error);
940E('ERR_HTTP2_PAYLOAD_FORBIDDEN',
941  'Responses with %s status must not have a payload', Error);
942E('ERR_HTTP2_PING_CANCEL', 'HTTP2 ping cancelled', Error);
943E('ERR_HTTP2_PING_LENGTH', 'HTTP2 ping payload must be 8 bytes', RangeError);
944E('ERR_HTTP2_PSEUDOHEADER_NOT_ALLOWED',
945  'Cannot set HTTP/2 pseudo-headers', TypeError);
946E('ERR_HTTP2_PUSH_DISABLED', 'HTTP/2 client has disabled push streams', Error);
947E('ERR_HTTP2_SEND_FILE', 'Directories cannot be sent', Error);
948E('ERR_HTTP2_SEND_FILE_NOSEEK',
949  'Offset or length can only be specified for regular files', Error);
950E('ERR_HTTP2_SESSION_ERROR', 'Session closed with error code %s', Error);
951E('ERR_HTTP2_SETTINGS_CANCEL', 'HTTP2 session settings canceled', Error);
952E('ERR_HTTP2_SOCKET_BOUND',
953  'The socket is already bound to an Http2Session', Error);
954E('ERR_HTTP2_SOCKET_UNBOUND',
955  'The socket has been disconnected from the Http2Session', Error);
956E('ERR_HTTP2_STATUS_101',
957  'HTTP status code 101 (Switching Protocols) is forbidden in HTTP/2', Error);
958E('ERR_HTTP2_STATUS_INVALID', 'Invalid status code: %s', RangeError);
959E('ERR_HTTP2_STREAM_CANCEL', function(error) {
960  let msg = 'The pending stream has been canceled';
961  if (error) {
962    this.cause = error;
963    if (typeof error.message === 'string')
964      msg += ` (caused by: ${error.message})`;
965  }
966  return msg;
967}, Error);
968E('ERR_HTTP2_STREAM_ERROR', 'Stream closed with error code %s', Error);
969E('ERR_HTTP2_STREAM_SELF_DEPENDENCY',
970  'A stream cannot depend on itself', Error);
971E('ERR_HTTP2_TRAILERS_ALREADY_SENT',
972  'Trailing headers have already been sent', Error);
973E('ERR_HTTP2_TRAILERS_NOT_READY',
974  'Trailing headers cannot be sent until after the wantTrailers event is ' +
975  'emitted', Error);
976E('ERR_HTTP2_UNSUPPORTED_PROTOCOL', 'protocol "%s" is unsupported.', Error);
977E('ERR_HTTP_HEADERS_SENT',
978  'Cannot %s headers after they are sent to the client', Error);
979E('ERR_HTTP_INVALID_HEADER_VALUE',
980  'Invalid value "%s" for header "%s"', TypeError);
981E('ERR_HTTP_INVALID_STATUS_CODE', 'Invalid status code: %s', RangeError);
982E('ERR_HTTP_REQUEST_TIMEOUT', 'Request timeout', Error);
983E('ERR_HTTP_TRAILER_INVALID',
984  'Trailers are invalid with this transfer encoding', Error);
985E('ERR_INCOMPATIBLE_OPTION_PAIR',
986  'Option "%s" cannot be used in combination with option "%s"', TypeError);
987E('ERR_INPUT_TYPE_NOT_ALLOWED', '--input-type can only be used with string ' +
988  'input via --eval, --print, or STDIN', Error);
989E('ERR_INSPECTOR_ALREADY_ACTIVATED',
990  'Inspector is already activated. Close it with inspector.close() ' +
991  'before activating it again.',
992  Error);
993E('ERR_INSPECTOR_ALREADY_CONNECTED', '%s is already connected', Error);
994E('ERR_INSPECTOR_CLOSED', 'Session was closed', Error);
995E('ERR_INSPECTOR_COMMAND', 'Inspector error %d: %s', Error);
996E('ERR_INSPECTOR_NOT_ACTIVE', 'Inspector is not active', Error);
997E('ERR_INSPECTOR_NOT_AVAILABLE', 'Inspector is not available', Error);
998E('ERR_INSPECTOR_NOT_CONNECTED', 'Session is not connected', Error);
999E('ERR_INSPECTOR_NOT_WORKER', 'Current thread is not a worker', Error);
1000E('ERR_INTERNAL_ASSERTION', (message) => {
1001  const suffix = 'This is caused by either a bug in Node.js ' +
1002    'or incorrect usage of Node.js internals.\n' +
1003    'Please open an issue with this stack trace at ' +
1004    'https://github.com/nodejs/node/issues\n';
1005  return message === undefined ? suffix : `${message}\n${suffix}`;
1006}, Error);
1007E('ERR_INVALID_ADDRESS_FAMILY', function(addressType, host, port) {
1008  this.host = host;
1009  this.port = port;
1010  return `Invalid address family: ${addressType} ${host}:${port}`;
1011}, RangeError);
1012E('ERR_INVALID_ARG_TYPE',
1013  (name, expected, actual) => {
1014    assert(typeof name === 'string', "'name' must be a string");
1015    if (!ArrayIsArray(expected)) {
1016      expected = [expected];
1017    }
1018
1019    let msg = 'The ';
1020    if (StringPrototypeEndsWith(name, ' argument')) {
1021      // For cases like 'first argument'
1022      msg += `${name} `;
1023    } else {
1024      const type = StringPrototypeIncludes(name, '.') ? 'property' : 'argument';
1025      msg += `"${name}" ${type} `;
1026    }
1027    msg += 'must be ';
1028
1029    const types = [];
1030    const instances = [];
1031    const other = [];
1032
1033    for (const value of expected) {
1034      assert(typeof value === 'string',
1035             'All expected entries have to be of type string');
1036      if (ArrayPrototypeIncludes(kTypes, value)) {
1037        ArrayPrototypePush(types, StringPrototypeToLowerCase(value));
1038      } else if (RegExpPrototypeTest(classRegExp, value)) {
1039        ArrayPrototypePush(instances, value);
1040      } else {
1041        assert(value !== 'object',
1042               'The value "object" should be written as "Object"');
1043        ArrayPrototypePush(other, value);
1044      }
1045    }
1046
1047    // Special handle `object` in case other instances are allowed to outline
1048    // the differences between each other.
1049    if (instances.length > 0) {
1050      const pos = ArrayPrototypeIndexOf(types, 'object');
1051      if (pos !== -1) {
1052        ArrayPrototypeSplice(types, pos, 1);
1053        ArrayPrototypePush(instances, 'Object');
1054      }
1055    }
1056
1057    if (types.length > 0) {
1058      if (types.length > 2) {
1059        const last = ArrayPrototypePop(types);
1060        msg += `one of type ${ArrayPrototypeJoin(types, ', ')}, or ${last}`;
1061      } else if (types.length === 2) {
1062        msg += `one of type ${types[0]} or ${types[1]}`;
1063      } else {
1064        msg += `of type ${types[0]}`;
1065      }
1066      if (instances.length > 0 || other.length > 0)
1067        msg += ' or ';
1068    }
1069
1070    if (instances.length > 0) {
1071      if (instances.length > 2) {
1072        const last = ArrayPrototypePop(instances);
1073        msg +=
1074          `an instance of ${ArrayPrototypeJoin(instances, ', ')}, or ${last}`;
1075      } else {
1076        msg += `an instance of ${instances[0]}`;
1077        if (instances.length === 2) {
1078          msg += ` or ${instances[1]}`;
1079        }
1080      }
1081      if (other.length > 0)
1082        msg += ' or ';
1083    }
1084
1085    if (other.length > 0) {
1086      if (other.length > 2) {
1087        const last = ArrayPrototypePop(other);
1088        msg += `one of ${ArrayPrototypeJoin(other, ', ')}, or ${last}`;
1089      } else if (other.length === 2) {
1090        msg += `one of ${other[0]} or ${other[1]}`;
1091      } else {
1092        if (StringPrototypeToLowerCase(other[0]) !== other[0])
1093          msg += 'an ';
1094        msg += `${other[0]}`;
1095      }
1096    }
1097
1098    if (actual == null) {
1099      msg += `. Received ${actual}`;
1100    } else if (typeof actual === 'function' && actual.name) {
1101      msg += `. Received function ${actual.name}`;
1102    } else if (typeof actual === 'object') {
1103      if (actual.constructor && actual.constructor.name) {
1104        msg += `. Received an instance of ${actual.constructor.name}`;
1105      } else {
1106        const inspected = lazyInternalUtilInspect()
1107          .inspect(actual, { depth: -1 });
1108        msg += `. Received ${inspected}`;
1109      }
1110    } else {
1111      let inspected = lazyInternalUtilInspect()
1112        .inspect(actual, { colors: false });
1113      if (inspected.length > 25)
1114        inspected = `${StringPrototypeSlice(inspected, 0, 25)}...`;
1115      msg += `. Received type ${typeof actual} (${inspected})`;
1116    }
1117    return msg;
1118  }, TypeError);
1119E('ERR_INVALID_ARG_VALUE', (name, value, reason = 'is invalid') => {
1120  let inspected = lazyInternalUtilInspect().inspect(value);
1121  if (inspected.length > 128) {
1122    inspected = `${StringPrototypeSlice(inspected, 0, 128)}...`;
1123  }
1124  return `The argument '${name}' ${reason}. Received ${inspected}`;
1125}, TypeError, RangeError);
1126E('ERR_INVALID_ASYNC_ID', 'Invalid %s value: %s', RangeError);
1127E('ERR_INVALID_BUFFER_SIZE',
1128  'Buffer size must be a multiple of %s', RangeError);
1129E('ERR_INVALID_CALLBACK',
1130  'Callback must be a function. Received %O', TypeError);
1131E('ERR_INVALID_CHAR',
1132  // Using a default argument here is important so the argument is not counted
1133  // towards `Function#length`.
1134  (name, field = undefined) => {
1135    let msg = `Invalid character in ${name}`;
1136    if (field !== undefined) {
1137      msg += ` ["${field}"]`;
1138    }
1139    return msg;
1140  }, TypeError);
1141E('ERR_INVALID_CURSOR_POS',
1142  'Cannot set cursor row without setting its column', TypeError);
1143E('ERR_INVALID_FD',
1144  '"fd" must be a positive integer: %s', RangeError);
1145E('ERR_INVALID_FD_TYPE', 'Unsupported fd type: %s', TypeError);
1146E('ERR_INVALID_FILE_URL_HOST',
1147  'File URL host must be "localhost" or empty on %s', TypeError);
1148E('ERR_INVALID_FILE_URL_PATH', 'File URL path %s', TypeError);
1149E('ERR_INVALID_HANDLE_TYPE', 'This handle type cannot be sent', TypeError);
1150E('ERR_INVALID_HTTP_TOKEN', '%s must be a valid HTTP token ["%s"]', TypeError);
1151E('ERR_INVALID_IP_ADDRESS', 'Invalid IP address: %s', TypeError);
1152E('ERR_INVALID_MODULE_SPECIFIER', (request, reason, base = undefined) => {
1153  return `Invalid module "${request}" ${reason}${base ?
1154    ` imported from ${base}` : ''}`;
1155}, TypeError);
1156E('ERR_INVALID_OPT_VALUE', (name, value, reason = '') => {
1157  let inspected = typeof value === 'string' ?
1158    value : lazyInternalUtilInspect().inspect(value);
1159  if (inspected.length > 128) inspected = `${inspected.slice(0, 128)}...`;
1160  if (reason) reason = '. ' + reason;
1161  return `The value "${inspected}" is invalid for option "${name}"` + reason;
1162}, TypeError, RangeError);
1163E('ERR_INVALID_OPT_VALUE_ENCODING',
1164  'The value "%s" is invalid for option "encoding"', TypeError);
1165E('ERR_INVALID_PACKAGE_CONFIG', (path, base, message) => {
1166  return `Invalid package config ${path}${base ? ` while importing ${base}` :
1167    ''}${message ? `. ${message}` : ''}`;
1168}, Error);
1169E('ERR_INVALID_PACKAGE_TARGET',
1170  (pkgPath, key, target, isImport = false, base = undefined) => {
1171    const relError = typeof target === 'string' && !isImport &&
1172      target.length && !StringPrototypeStartsWith(target, './');
1173    if (key === '.') {
1174      assert(isImport === false);
1175      return `Invalid "exports" main target ${JSONStringify(target)} defined ` +
1176        `in the package config ${pkgPath}package.json${base ?
1177          ` imported from ${base}` : ''}${relError ?
1178          '; targets must start with "./"' : ''}`;
1179    }
1180    return `Invalid "${isImport ? 'imports' : 'exports'}" target ${
1181      JSONStringify(target)} defined for '${key}' in the package config ${
1182      pkgPath}package.json${base ? ` imported from ${base}` : ''}${relError ?
1183      '; targets must start with "./"' : ''}`;
1184  }, Error);
1185E('ERR_INVALID_PERFORMANCE_MARK',
1186  'The "%s" performance mark has not been set', Error);
1187E('ERR_INVALID_PROTOCOL',
1188  'Protocol "%s" not supported. Expected "%s"',
1189  TypeError);
1190E('ERR_INVALID_REPL_EVAL_CONFIG',
1191  'Cannot specify both "breakEvalOnSigint" and "eval" for REPL', TypeError);
1192E('ERR_INVALID_REPL_INPUT', '%s', TypeError);
1193E('ERR_INVALID_RETURN_PROPERTY', (input, name, prop, value) => {
1194  return `Expected a valid ${input} to be returned for the "${prop}" from the` +
1195         ` "${name}" function but got ${value}.`;
1196}, TypeError);
1197E('ERR_INVALID_RETURN_PROPERTY_VALUE', (input, name, prop, value) => {
1198  let type;
1199  if (value && value.constructor && value.constructor.name) {
1200    type = `instance of ${value.constructor.name}`;
1201  } else {
1202    type = `type ${typeof value}`;
1203  }
1204  return `Expected ${input} to be returned for the "${prop}" from the` +
1205         ` "${name}" function but got ${type}.`;
1206}, TypeError);
1207E('ERR_INVALID_RETURN_VALUE', (input, name, value) => {
1208  let type;
1209  if (value && value.constructor && value.constructor.name) {
1210    type = `instance of ${value.constructor.name}`;
1211  } else {
1212    type = `type ${typeof value}`;
1213  }
1214  return `Expected ${input} to be returned from the "${name}"` +
1215         ` function but got ${type}.`;
1216}, TypeError);
1217E('ERR_INVALID_SYNC_FORK_INPUT',
1218  'Asynchronous forks do not support ' +
1219    'Buffer, TypedArray, DataView or string input: %s',
1220  TypeError);
1221E('ERR_INVALID_THIS', 'Value of "this" must be of type %s', TypeError);
1222E('ERR_INVALID_TUPLE', '%s must be an iterable %s tuple', TypeError);
1223E('ERR_INVALID_URI', 'URI malformed', URIError);
1224E('ERR_INVALID_URL', function(input) {
1225  this.input = input;
1226  return `Invalid URL: ${input}`;
1227}, TypeError);
1228E('ERR_INVALID_URL_SCHEME',
1229  (expected) => {
1230    if (typeof expected === 'string')
1231      expected = [expected];
1232    assert(expected.length <= 2);
1233    const res = expected.length === 2 ?
1234      `one of scheme ${expected[0]} or ${expected[1]}` :
1235      `of scheme ${expected[0]}`;
1236    return `The URL must be ${res}`;
1237  }, TypeError);
1238E('ERR_IPC_CHANNEL_CLOSED', 'Channel closed', Error);
1239E('ERR_IPC_DISCONNECTED', 'IPC channel is already disconnected', Error);
1240E('ERR_IPC_ONE_PIPE', 'Child process can have only one IPC pipe', Error);
1241E('ERR_IPC_SYNC_FORK', 'IPC cannot be used with synchronous forks', Error);
1242E('ERR_MANIFEST_ASSERT_INTEGRITY',
1243  (moduleURL, realIntegrities) => {
1244    let msg = `The content of "${
1245      moduleURL
1246    }" does not match the expected integrity.`;
1247    if (realIntegrities.size) {
1248      const sri = ArrayPrototypeJoin(
1249        ArrayFrom(realIntegrities.entries(),
1250                  ({ 0: alg, 1: dgs }) => `${alg}-${dgs}`),
1251        ' '
1252      );
1253      msg += ` Integrities found are: ${sri}`;
1254    } else {
1255      msg += ' The resource was not found in the policy.';
1256    }
1257    return msg;
1258  }, Error);
1259E('ERR_MANIFEST_DEPENDENCY_MISSING',
1260  'Manifest resource %s does not list %s as a dependency specifier for ' +
1261  'conditions: %s',
1262  Error);
1263E('ERR_MANIFEST_INTEGRITY_MISMATCH',
1264  'Manifest resource %s has multiple entries but integrity lists do not match',
1265  SyntaxError);
1266E('ERR_MANIFEST_INVALID_RESOURCE_FIELD',
1267  'Manifest resource %s has invalid property value for %s',
1268  TypeError);
1269E('ERR_MANIFEST_INVALID_SPECIFIER',
1270  'Manifest resource %s has invalid dependency mapping %s',
1271  TypeError);
1272E('ERR_MANIFEST_TDZ', 'Manifest initialization has not yet run', Error);
1273E('ERR_MANIFEST_UNKNOWN_ONERROR',
1274  'Manifest specified unknown error behavior "%s".',
1275  SyntaxError);
1276E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error);
1277E('ERR_MISSING_ARGS',
1278  (...args) => {
1279    assert(args.length > 0, 'At least one arg needs to be specified');
1280    let msg = 'The ';
1281    const len = args.length;
1282    const wrap = (a) => `"${a}"`;
1283    args = ArrayPrototypeMap(
1284      args,
1285      (a) => (ArrayIsArray(a) ?
1286        ArrayPrototypeJoin(ArrayPrototypeMap(a, wrap), ' or ') :
1287        wrap(a))
1288    );
1289    switch (len) {
1290      case 1:
1291        msg += `${args[0]} argument`;
1292        break;
1293      case 2:
1294        msg += `${args[0]} and ${args[1]} arguments`;
1295        break;
1296      default:
1297        msg += ArrayPrototypeJoin(ArrayPrototypeSlice(args, 0, len - 1), ', ');
1298        msg += `, and ${args[len - 1]} arguments`;
1299        break;
1300    }
1301    return `${msg} must be specified`;
1302  }, TypeError);
1303E('ERR_MISSING_OPTION', '%s is required', TypeError);
1304E('ERR_MODULE_NOT_FOUND', (path, base, type = 'package') => {
1305  return `Cannot find ${type} '${path}' imported from ${base}`;
1306}, Error);
1307E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error);
1308E('ERR_NAPI_CONS_FUNCTION', 'Constructor must be a function', TypeError);
1309E('ERR_NAPI_INVALID_DATAVIEW_ARGS',
1310  'byte_offset + byte_length should be less than or equal to the size in ' +
1311    'bytes of the array passed in',
1312  RangeError);
1313E('ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT',
1314  'start offset of %s should be a multiple of %s', RangeError);
1315E('ERR_NAPI_INVALID_TYPEDARRAY_LENGTH',
1316  'Invalid typed array length', RangeError);
1317E('ERR_NO_CRYPTO',
1318  'Node.js is not compiled with OpenSSL crypto support', Error);
1319E('ERR_NO_ICU',
1320  '%s is not supported on Node.js compiled without ICU', TypeError);
1321E('ERR_OPERATION_FAILED', 'Operation failed: %s', Error);
1322E('ERR_OUT_OF_RANGE',
1323  (str, range, input, replaceDefaultBoolean = false) => {
1324    assert(range, 'Missing "range" argument');
1325    let msg = replaceDefaultBoolean ? str :
1326      `The value of "${str}" is out of range.`;
1327    let received;
1328    if (NumberIsInteger(input) && MathAbs(input) > 2 ** 32) {
1329      received = addNumericalSeparator(String(input));
1330    } else if (typeof input === 'bigint') {
1331      received = String(input);
1332      if (input > 2n ** 32n || input < -(2n ** 32n)) {
1333        received = addNumericalSeparator(received);
1334      }
1335      received += 'n';
1336    } else {
1337      received = lazyInternalUtilInspect().inspect(input);
1338    }
1339    msg += ` It must be ${range}. Received ${received}`;
1340    return msg;
1341  }, RangeError);
1342E('ERR_PACKAGE_IMPORT_NOT_DEFINED', (specifier, packagePath, base) => {
1343  return `Package import specifier "${specifier}" is not defined${packagePath ?
1344    ` in package ${packagePath}package.json` : ''} imported from ${base}`;
1345}, TypeError);
1346E('ERR_PACKAGE_PATH_NOT_EXPORTED', (pkgPath, subpath, base = undefined) => {
1347  if (subpath === '.')
1348    return `No "exports" main defined in ${pkgPath}package.json${base ?
1349      ` imported from ${base}` : ''}`;
1350  return `Package subpath '${subpath}' is not defined by "exports" in ${
1351    pkgPath}package.json${base ? ` imported from ${base}` : ''}`;
1352}, Error);
1353E('ERR_REQUIRE_ESM',
1354  (filename, parentPath = null, packageJsonPath = null) => {
1355    let msg = `Must use import to load ES Module: ${filename}`;
1356    if (parentPath && packageJsonPath) {
1357      const path = require('path');
1358      const basename = path.basename(filename) === path.basename(parentPath) ?
1359        filename : path.basename(filename);
1360      msg +=
1361        '\nrequire() of ES modules is not supported.\nrequire() of ' +
1362        `${filename} from ${parentPath} ` +
1363        'is an ES module file as it is a .js file whose nearest parent ' +
1364        'package.json contains "type": "module" which defines all .js ' +
1365        'files in that package scope as ES modules.\nInstead rename ' +
1366        `${basename} to end in .cjs, change the requiring code to use ` +
1367        'import(), or remove "type": "module" from ' +
1368        `${packageJsonPath}.\n`;
1369      return msg;
1370    }
1371    return msg;
1372  }, Error);
1373E('ERR_SCRIPT_EXECUTION_INTERRUPTED',
1374  'Script execution was interrupted by `SIGINT`', Error);
1375E('ERR_SERVER_ALREADY_LISTEN',
1376  'Listen method has been called more than once without closing.', Error);
1377E('ERR_SERVER_NOT_RUNNING', 'Server is not running.', Error);
1378E('ERR_SOCKET_ALREADY_BOUND', 'Socket is already bound', Error);
1379E('ERR_SOCKET_BAD_BUFFER_SIZE',
1380  'Buffer size must be a positive integer', TypeError);
1381E('ERR_SOCKET_BAD_PORT', (name, port, allowZero = true) => {
1382  assert(typeof allowZero === 'boolean',
1383         "The 'allowZero' argument must be of type boolean.");
1384  const operator = allowZero ? '>=' : '>';
1385  return `${name} should be ${operator} 0 and < 65536. Received ${port}.`;
1386}, RangeError);
1387E('ERR_SOCKET_BAD_TYPE',
1388  'Bad socket type specified. Valid types are: udp4, udp6', TypeError);
1389E('ERR_SOCKET_BUFFER_SIZE',
1390  'Could not get or set buffer size',
1391  SystemError);
1392E('ERR_SOCKET_CLOSED', 'Socket is closed', Error);
1393E('ERR_SOCKET_DGRAM_IS_CONNECTED', 'Already connected', Error);
1394E('ERR_SOCKET_DGRAM_NOT_CONNECTED', 'Not connected', Error);
1395E('ERR_SOCKET_DGRAM_NOT_RUNNING', 'Not running', Error);
1396E('ERR_SRI_PARSE',
1397  'Subresource Integrity string %j had an unexpected %j at position %d',
1398  SyntaxError);
1399E('ERR_STREAM_ALREADY_FINISHED',
1400  'Cannot call %s after a stream was finished',
1401  Error);
1402E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error);
1403E('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error);
1404E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
1405E('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error);
1406E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error);
1407E('ERR_STREAM_UNSHIFT_AFTER_END_EVENT',
1408  'stream.unshift() after end event', Error);
1409E('ERR_STREAM_WRAP', 'Stream has StringDecoder set or is in objectMode', Error);
1410E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error);
1411E('ERR_SYNTHETIC', 'JavaScript Callstack', Error);
1412E('ERR_SYSTEM_ERROR', 'A system error occurred', SystemError);
1413E('ERR_TLS_CERT_ALTNAME_FORMAT', 'Invalid subject alternative name string',
1414  SyntaxError);
1415E('ERR_TLS_CERT_ALTNAME_INVALID', function(reason, host, cert) {
1416  this.reason = reason;
1417  this.host = host;
1418  this.cert = cert;
1419  return `Hostname/IP does not match certificate's altnames: ${reason}`;
1420}, Error);
1421E('ERR_TLS_DH_PARAM_SIZE', 'DH parameter size %s is less than 2048', Error);
1422E('ERR_TLS_HANDSHAKE_TIMEOUT', 'TLS handshake timeout', Error);
1423E('ERR_TLS_INVALID_CONTEXT', '%s must be a SecureContext', TypeError);
1424E('ERR_TLS_INVALID_PROTOCOL_VERSION',
1425  '%j is not a valid %s TLS protocol version', TypeError);
1426E('ERR_TLS_INVALID_STATE', 'TLS socket connection must be securely established',
1427  Error);
1428E('ERR_TLS_PROTOCOL_VERSION_CONFLICT',
1429  'TLS protocol version %j conflicts with secureProtocol %j', TypeError);
1430E('ERR_TLS_RENEGOTIATION_DISABLED',
1431  'TLS session renegotiation disabled for this socket', Error);
1432
1433// This should probably be a `TypeError`.
1434E('ERR_TLS_REQUIRED_SERVER_NAME',
1435  '"servername" is required parameter for Server.addContext', Error);
1436E('ERR_TLS_SESSION_ATTACK', 'TLS session renegotiation attack detected', Error);
1437E('ERR_TLS_SNI_FROM_SERVER',
1438  'Cannot issue SNI from a TLS server-side socket', Error);
1439E('ERR_TRACE_EVENTS_CATEGORY_REQUIRED',
1440  'At least one category is required', TypeError);
1441E('ERR_TRACE_EVENTS_UNAVAILABLE', 'Trace events are unavailable', Error);
1442E('ERR_TRANSFORM_ALREADY_TRANSFORMING',
1443  'Calling transform done when still transforming', Error);
1444
1445// This should probably be a `RangeError`.
1446E('ERR_TRANSFORM_WITH_LENGTH_0',
1447  'Calling transform done when writableState.length != 0', Error);
1448E('ERR_TTY_INIT_FAILED', 'TTY initialization failed', SystemError);
1449E('ERR_UNAVAILABLE_DURING_EXIT', 'Cannot call function in process exit ' +
1450  'handler', Error);
1451E('ERR_UNCAUGHT_EXCEPTION_CAPTURE_ALREADY_SET',
1452  '`process.setupUncaughtExceptionCapture()` was called while a capture ' +
1453    'callback was already active',
1454  Error);
1455E('ERR_UNESCAPED_CHARACTERS', '%s contains unescaped characters', TypeError);
1456E('ERR_UNHANDLED_ERROR',
1457  // Using a default argument here is important so the argument is not counted
1458  // towards `Function#length`.
1459  (err = undefined) => {
1460    const msg = 'Unhandled error.';
1461    if (err === undefined) return msg;
1462    return `${msg} (${err})`;
1463  }, Error);
1464E('ERR_UNKNOWN_BUILTIN_MODULE', 'No such built-in module: %s', Error);
1465E('ERR_UNKNOWN_CREDENTIAL', '%s identifier does not exist: %s', Error);
1466E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError);
1467E('ERR_UNKNOWN_FILE_EXTENSION',
1468  'Unknown file extension "%s" for %s',
1469  TypeError);
1470E('ERR_UNKNOWN_MODULE_FORMAT', 'Unknown module format: %s', RangeError);
1471E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s', TypeError);
1472E('ERR_UNSUPPORTED_DIR_IMPORT', "Directory import '%s' is not supported " +
1473'resolving ES modules imported from %s', Error);
1474E('ERR_UNSUPPORTED_ESM_URL_SCHEME', (url) => {
1475  let msg = 'Only file and data URLs are supported by the default ESM loader';
1476  if (isWindows && url.protocol.length === 2) {
1477    msg +=
1478      '. On Windows, absolute paths must be valid file:// URLs';
1479  }
1480  msg += `. Received protocol '${url.protocol}'`;
1481  return msg;
1482}, Error);
1483
1484// This should probably be a `TypeError`.
1485E('ERR_VALID_PERFORMANCE_ENTRY_TYPE',
1486  'At least one valid performance entry type is required', Error);
1487E('ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING',
1488  'A dynamic import callback was not specified.', TypeError);
1489E('ERR_VM_MODULE_ALREADY_LINKED', 'Module has already been linked', Error);
1490E('ERR_VM_MODULE_CANNOT_CREATE_CACHED_DATA',
1491  'Cached data cannot be created for a module which has been evaluated', Error);
1492E('ERR_VM_MODULE_DIFFERENT_CONTEXT',
1493  'Linked modules must use the same context', Error);
1494E('ERR_VM_MODULE_LINKING_ERRORED',
1495  'Linking has already failed for the provided module', Error);
1496E('ERR_VM_MODULE_NOT_MODULE',
1497  'Provided module is not an instance of Module', Error);
1498E('ERR_VM_MODULE_STATUS', 'Module status %s', Error);
1499E('ERR_WASI_ALREADY_STARTED', 'WASI instance has already started', Error);
1500E('ERR_WORKER_INIT_FAILED', 'Worker initialization failure: %s', Error);
1501E('ERR_WORKER_INVALID_EXEC_ARGV', (errors, msg = 'invalid execArgv flags') =>
1502  `Initiated Worker with ${msg}: ${ArrayPrototypeJoin(errors, ', ')}`,
1503  Error);
1504E('ERR_WORKER_NOT_RUNNING', 'Worker instance not running', Error);
1505E('ERR_WORKER_OUT_OF_MEMORY',
1506  'Worker terminated due to reaching memory limit: %s', Error);
1507E('ERR_WORKER_PATH', (filename) =>
1508  'The worker script or module filename must be an absolute path or a ' +
1509  'relative path starting with \'./\' or \'../\'.' +
1510  (StringPrototypeStartsWith(filename, 'file://') ?
1511    ' Wrap file:// URLs with `new URL`.' : ''
1512  ) +
1513  (StringPrototypeStartsWith(filename, 'data:text/javascript') ?
1514    ' Wrap data: URLs with `new URL`.' : ''
1515  ) +
1516  ` Received "${filename}"`,
1517  TypeError);
1518E('ERR_WORKER_UNSERIALIZABLE_ERROR',
1519  'Serializing an uncaught exception failed', Error);
1520E('ERR_WORKER_UNSUPPORTED_EXTENSION',
1521  'The worker script extension must be ".js", ".mjs", or ".cjs". Received "%s"',
1522  TypeError);
1523E('ERR_WORKER_UNSUPPORTED_OPERATION',
1524  '%s is not supported in workers', TypeError);
1525E('ERR_ZLIB_INITIALIZATION_FAILED', 'Initialization failed', Error);
1526