errors.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. "use strict";
  2. // The whole point behind this internal module is to allow Node.js to no
  3. // longer be forced to treat every error message change as a semver-major
  4. // change. The NodeError classes here all expose a `code` property whose
  5. // value statically and permanently identifies the error. While the error
  6. // message may change, the code should not.
  7. Object.defineProperty(exports, "__esModule", { value: true });
  8. exports.E = exports.AssertionError = exports.message = exports.RangeError = exports.TypeError = exports.Error = void 0;
  9. const assert = require("assert");
  10. const util = require("util");
  11. const kCode = typeof Symbol === 'undefined' ? '_kCode' : Symbol('code');
  12. const messages = {}; // new Map();
  13. function makeNodeError(Base) {
  14. return class NodeError extends Base {
  15. constructor(key, ...args) {
  16. super(message(key, args));
  17. this.code = key;
  18. this[kCode] = key;
  19. this.name = `${super.name} [${this[kCode]}]`;
  20. }
  21. };
  22. }
  23. const g = typeof globalThis !== 'undefined' ? globalThis : global;
  24. class AssertionError extends g.Error {
  25. constructor(options) {
  26. if (typeof options !== 'object' || options === null) {
  27. throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object');
  28. }
  29. if (options.message) {
  30. super(options.message);
  31. }
  32. else {
  33. super(`${util.inspect(options.actual).slice(0, 128)} ` +
  34. `${options.operator} ${util.inspect(options.expected).slice(0, 128)}`);
  35. }
  36. this.generatedMessage = !options.message;
  37. this.name = 'AssertionError [ERR_ASSERTION]';
  38. this.code = 'ERR_ASSERTION';
  39. this.actual = options.actual;
  40. this.expected = options.expected;
  41. this.operator = options.operator;
  42. exports.Error.captureStackTrace(this, options.stackStartFunction);
  43. }
  44. }
  45. exports.AssertionError = AssertionError;
  46. function message(key, args) {
  47. assert.strictEqual(typeof key, 'string');
  48. // const msg = messages.get(key);
  49. const msg = messages[key];
  50. assert(msg, `An invalid error message key was used: ${key}.`);
  51. let fmt;
  52. if (typeof msg === 'function') {
  53. fmt = msg;
  54. }
  55. else {
  56. fmt = util.format;
  57. if (args === undefined || args.length === 0)
  58. return msg;
  59. args.unshift(msg);
  60. }
  61. return String(fmt.apply(null, args));
  62. }
  63. exports.message = message;
  64. // Utility function for registering the error codes. Only used here. Exported
  65. // *only* to allow for testing.
  66. function E(sym, val) {
  67. messages[sym] = typeof val === 'function' ? val : String(val);
  68. }
  69. exports.E = E;
  70. exports.Error = makeNodeError(g.Error);
  71. exports.TypeError = makeNodeError(g.TypeError);
  72. exports.RangeError = makeNodeError(g.RangeError);
  73. // To declare an error message, use the E(sym, val) function above. The sym
  74. // must be an upper case string. The val can be either a function or a string.
  75. // The return value of the function must be a string.
  76. // Examples:
  77. // E('EXAMPLE_KEY1', 'This is the error value');
  78. // E('EXAMPLE_KEY2', (a, b) => return `${a} ${b}`);
  79. //
  80. // Once an error code has been assigned, the code itself MUST NOT change and
  81. // any given error code must never be reused to identify a different error.
  82. //
  83. // Any error code added here should also be added to the documentation
  84. //
  85. // Note: Please try to keep these in alphabetical order
  86. E('ERR_ARG_NOT_ITERABLE', '%s must be iterable');
  87. E('ERR_ASSERTION', '%s');
  88. E('ERR_BUFFER_OUT_OF_BOUNDS', bufferOutOfBounds);
  89. E('ERR_CHILD_CLOSED_BEFORE_REPLY', 'Child closed before reply received');
  90. E('ERR_CONSOLE_WRITABLE_STREAM', 'Console expects a writable stream instance for %s');
  91. E('ERR_CPU_USAGE', 'Unable to obtain cpu usage %s');
  92. E('ERR_DNS_SET_SERVERS_FAILED', (err, servers) => `c-ares failed to set servers: "${err}" [${servers}]`);
  93. E('ERR_FALSY_VALUE_REJECTION', 'Promise was rejected with falsy value');
  94. E('ERR_ENCODING_NOT_SUPPORTED', enc => `The "${enc}" encoding is not supported`);
  95. E('ERR_ENCODING_INVALID_ENCODED_DATA', enc => `The encoded data was not valid for encoding ${enc}`);
  96. E('ERR_HTTP_HEADERS_SENT', 'Cannot render headers after they are sent to the client');
  97. E('ERR_HTTP_INVALID_STATUS_CODE', 'Invalid status code: %s');
  98. E('ERR_HTTP_TRAILER_INVALID', 'Trailers are invalid with this transfer encoding');
  99. E('ERR_INDEX_OUT_OF_RANGE', 'Index out of range');
  100. E('ERR_INVALID_ARG_TYPE', invalidArgType);
  101. E('ERR_INVALID_ARRAY_LENGTH', (name, len, actual) => {
  102. assert.strictEqual(typeof actual, 'number');
  103. return `The array "${name}" (length ${actual}) must be of length ${len}.`;
  104. });
  105. E('ERR_INVALID_BUFFER_SIZE', 'Buffer size must be a multiple of %s');
  106. E('ERR_INVALID_CALLBACK', 'Callback must be a function');
  107. E('ERR_INVALID_CHAR', 'Invalid character in %s');
  108. E('ERR_INVALID_CURSOR_POS', 'Cannot set cursor row without setting its column');
  109. E('ERR_INVALID_FD', '"fd" must be a positive integer: %s');
  110. E('ERR_INVALID_FILE_URL_HOST', 'File URL host must be "localhost" or empty on %s');
  111. E('ERR_INVALID_FILE_URL_PATH', 'File URL path %s');
  112. E('ERR_INVALID_HANDLE_TYPE', 'This handle type cannot be sent');
  113. E('ERR_INVALID_IP_ADDRESS', 'Invalid IP address: %s');
  114. E('ERR_INVALID_OPT_VALUE', (name, value) => {
  115. return `The value "${String(value)}" is invalid for option "${name}"`;
  116. });
  117. E('ERR_INVALID_OPT_VALUE_ENCODING', value => `The value "${String(value)}" is invalid for option "encoding"`);
  118. E('ERR_INVALID_REPL_EVAL_CONFIG', 'Cannot specify both "breakEvalOnSigint" and "eval" for REPL');
  119. E('ERR_INVALID_SYNC_FORK_INPUT', 'Asynchronous forks do not support Buffer, Uint8Array or string input: %s');
  120. E('ERR_INVALID_THIS', 'Value of "this" must be of type %s');
  121. E('ERR_INVALID_TUPLE', '%s must be an iterable %s tuple');
  122. E('ERR_INVALID_URL', 'Invalid URL: %s');
  123. E('ERR_INVALID_URL_SCHEME', expected => `The URL must be ${oneOf(expected, 'scheme')}`);
  124. E('ERR_IPC_CHANNEL_CLOSED', 'Channel closed');
  125. E('ERR_IPC_DISCONNECTED', 'IPC channel is already disconnected');
  126. E('ERR_IPC_ONE_PIPE', 'Child process can have only one IPC pipe');
  127. E('ERR_IPC_SYNC_FORK', 'IPC cannot be used with synchronous forks');
  128. E('ERR_MISSING_ARGS', missingArgs);
  129. E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
  130. E('ERR_NAPI_CONS_FUNCTION', 'Constructor must be a function');
  131. E('ERR_NAPI_CONS_PROTOTYPE_OBJECT', 'Constructor.prototype must be an object');
  132. E('ERR_NO_CRYPTO', 'Node.js is not compiled with OpenSSL crypto support');
  133. E('ERR_NO_LONGER_SUPPORTED', '%s is no longer supported');
  134. E('ERR_PARSE_HISTORY_DATA', 'Could not parse history data in %s');
  135. E('ERR_SOCKET_ALREADY_BOUND', 'Socket is already bound');
  136. E('ERR_SOCKET_BAD_PORT', 'Port should be > 0 and < 65536');
  137. E('ERR_SOCKET_BAD_TYPE', 'Bad socket type specified. Valid types are: udp4, udp6');
  138. E('ERR_SOCKET_CANNOT_SEND', 'Unable to send data');
  139. E('ERR_SOCKET_CLOSED', 'Socket is closed');
  140. E('ERR_SOCKET_DGRAM_NOT_RUNNING', 'Not running');
  141. E('ERR_STDERR_CLOSE', 'process.stderr cannot be closed');
  142. E('ERR_STDOUT_CLOSE', 'process.stdout cannot be closed');
  143. E('ERR_STREAM_WRAP', 'Stream has StringDecoder set or is in objectMode');
  144. E('ERR_TLS_CERT_ALTNAME_INVALID', "Hostname/IP does not match certificate's altnames: %s");
  145. E('ERR_TLS_DH_PARAM_SIZE', size => `DH parameter size ${size} is less than 2048`);
  146. E('ERR_TLS_HANDSHAKE_TIMEOUT', 'TLS handshake timeout');
  147. E('ERR_TLS_RENEGOTIATION_FAILED', 'Failed to renegotiate');
  148. E('ERR_TLS_REQUIRED_SERVER_NAME', '"servername" is required parameter for Server.addContext');
  149. E('ERR_TLS_SESSION_ATTACK', 'TSL session renegotiation attack detected');
  150. E('ERR_TRANSFORM_ALREADY_TRANSFORMING', 'Calling transform done when still transforming');
  151. E('ERR_TRANSFORM_WITH_LENGTH_0', 'Calling transform done when writableState.length != 0');
  152. E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s');
  153. E('ERR_UNKNOWN_SIGNAL', 'Unknown signal: %s');
  154. E('ERR_UNKNOWN_STDIN_TYPE', 'Unknown stdin file type');
  155. E('ERR_UNKNOWN_STREAM_TYPE', 'Unknown stream file type');
  156. E('ERR_V8BREAKITERATOR', 'Full ICU data not installed. ' + 'See https://github.com/nodejs/node/wiki/Intl');
  157. function invalidArgType(name, expected, actual) {
  158. assert(name, 'name is required');
  159. // determiner: 'must be' or 'must not be'
  160. let determiner;
  161. if (expected.includes('not ')) {
  162. determiner = 'must not be';
  163. expected = expected.split('not ')[1];
  164. }
  165. else {
  166. determiner = 'must be';
  167. }
  168. let msg;
  169. if (Array.isArray(name)) {
  170. const names = name.map(val => `"${val}"`).join(', ');
  171. msg = `The ${names} arguments ${determiner} ${oneOf(expected, 'type')}`;
  172. }
  173. else if (name.includes(' argument')) {
  174. // for the case like 'first argument'
  175. msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`;
  176. }
  177. else {
  178. const type = name.includes('.') ? 'property' : 'argument';
  179. msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`;
  180. }
  181. // if actual value received, output it
  182. if (arguments.length >= 3) {
  183. msg += `. Received type ${actual !== null ? typeof actual : 'null'}`;
  184. }
  185. return msg;
  186. }
  187. function missingArgs(...args) {
  188. assert(args.length > 0, 'At least one arg needs to be specified');
  189. let msg = 'The ';
  190. const len = args.length;
  191. args = args.map(a => `"${a}"`);
  192. switch (len) {
  193. case 1:
  194. msg += `${args[0]} argument`;
  195. break;
  196. case 2:
  197. msg += `${args[0]} and ${args[1]} arguments`;
  198. break;
  199. default:
  200. msg += args.slice(0, len - 1).join(', ');
  201. msg += `, and ${args[len - 1]} arguments`;
  202. break;
  203. }
  204. return `${msg} must be specified`;
  205. }
  206. function oneOf(expected, thing) {
  207. assert(expected, 'expected is required');
  208. assert(typeof thing === 'string', 'thing is required');
  209. if (Array.isArray(expected)) {
  210. const len = expected.length;
  211. assert(len > 0, 'At least one expected value needs to be specified');
  212. // tslint:disable-next-line
  213. expected = expected.map(i => String(i));
  214. if (len > 2) {
  215. return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + expected[len - 1];
  216. }
  217. else if (len === 2) {
  218. return `one of ${thing} ${expected[0]} or ${expected[1]}`;
  219. }
  220. else {
  221. return `of ${thing} ${expected[0]}`;
  222. }
  223. }
  224. else {
  225. return `of ${thing} ${String(expected)}`;
  226. }
  227. }
  228. function bufferOutOfBounds(name, isWriting) {
  229. if (isWriting) {
  230. return 'Attempt to write outside buffer bounds';
  231. }
  232. else {
  233. return `"${name}" is outside of buffer bounds`;
  234. }
  235. }