errors.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. 'use strict';
  2. /**
  3. * @typedef {import('./mocha.js')} Mocha
  4. * @typedef {import('./runnable.js')} Runnable
  5. * @typedef {import('./types.d.ts').MochaTimeoutError} MochaTimeoutError
  6. * @typedef {import('./types.d.ts').PluginDefinition} PluginDefinition
  7. */
  8. const {format} = require('node:util');
  9. const { constants } = require('./error-constants.js');
  10. /**
  11. * Contains error codes, factory functions to create throwable error objects,
  12. * and warning/deprecation functions.
  13. * @module
  14. */
  15. /**
  16. * process.emitWarning or a polyfill
  17. * @see https://nodejs.org/api/process.html#process_process_emitwarning_warning_options
  18. * @ignore
  19. */
  20. const emitWarning = (msg, type) => {
  21. if (process.emitWarning) {
  22. process.emitWarning(msg, type);
  23. } else {
  24. /* istanbul ignore next */
  25. process.nextTick(function () {
  26. console.warn(type + ': ' + msg);
  27. });
  28. }
  29. };
  30. /**
  31. * Show a deprecation warning. Each distinct message is only displayed once.
  32. * Ignores empty messages.
  33. *
  34. * @param {string} [msg] - Warning to print
  35. * @private
  36. */
  37. const deprecate = msg => {
  38. msg = String(msg);
  39. if (msg && !deprecate.cache[msg]) {
  40. deprecate.cache[msg] = true;
  41. emitWarning(msg, 'DeprecationWarning');
  42. }
  43. };
  44. deprecate.cache = {};
  45. /**
  46. * Show a generic warning.
  47. * Ignores empty messages.
  48. *
  49. * @param {string} [msg] - Warning to print
  50. * @private
  51. */
  52. const warn = msg => {
  53. if (msg) {
  54. emitWarning(msg);
  55. }
  56. };
  57. /**
  58. * A set containing all string values of all Mocha error constants, for use by {@link isMochaError}.
  59. * @private
  60. */
  61. const MOCHA_ERRORS = new Set(Object.values(constants));
  62. /**
  63. * Creates an error object to be thrown when no files to be tested could be found using specified pattern.
  64. *
  65. * @public
  66. * @static
  67. * @param {string} message - Error message to be displayed.
  68. * @param {string} pattern - User-specified argument value.
  69. * @returns {Error} instance detailing the error condition
  70. */
  71. function createNoFilesMatchPatternError(message, pattern) {
  72. var err = new Error(message);
  73. err.code = constants.NO_FILES_MATCH_PATTERN;
  74. err.pattern = pattern;
  75. return err;
  76. }
  77. /**
  78. * Creates an error object to be thrown when the reporter specified in the options was not found.
  79. *
  80. * @public
  81. * @param {string} message - Error message to be displayed.
  82. * @param {string} reporter - User-specified reporter value.
  83. * @returns {Error} instance detailing the error condition
  84. */
  85. function createInvalidReporterError(message, reporter) {
  86. var err = new TypeError(message);
  87. err.code = constants.INVALID_REPORTER;
  88. err.reporter = reporter;
  89. return err;
  90. }
  91. /**
  92. * Creates an error object to be thrown when the interface specified in the options was not found.
  93. *
  94. * @public
  95. * @static
  96. * @param {string} message - Error message to be displayed.
  97. * @param {string} ui - User-specified interface value.
  98. * @returns {Error} instance detailing the error condition
  99. */
  100. function createInvalidInterfaceError(message, ui) {
  101. var err = new Error(message);
  102. err.code = constants.INVALID_INTERFACE;
  103. err.interface = ui;
  104. return err;
  105. }
  106. /**
  107. * Creates an error object to be thrown when a behavior, option, or parameter is unsupported.
  108. *
  109. * @public
  110. * @static
  111. * @param {string} message - Error message to be displayed.
  112. * @returns {Error} instance detailing the error condition
  113. */
  114. function createUnsupportedError(message) {
  115. var err = new Error(message);
  116. err.code = constants.UNSUPPORTED;
  117. return err;
  118. }
  119. /**
  120. * Creates an error object to be thrown when an argument is missing.
  121. *
  122. * @public
  123. * @static
  124. * @param {string} message - Error message to be displayed.
  125. * @param {string} argument - Argument name.
  126. * @param {string} expected - Expected argument datatype.
  127. * @returns {Error} instance detailing the error condition
  128. */
  129. function createMissingArgumentError(message, argument, expected) {
  130. return createInvalidArgumentTypeError(message, argument, expected);
  131. }
  132. /**
  133. * Creates an error object to be thrown when an argument did not use the supported type
  134. *
  135. * @public
  136. * @static
  137. * @param {string} message - Error message to be displayed.
  138. * @param {string} argument - Argument name.
  139. * @param {string} expected - Expected argument datatype.
  140. * @returns {Error} instance detailing the error condition
  141. */
  142. function createInvalidArgumentTypeError(message, argument, expected) {
  143. var err = new TypeError(message);
  144. err.code = constants.INVALID_ARG_TYPE;
  145. err.argument = argument;
  146. err.expected = expected;
  147. err.actual = typeof argument;
  148. return err;
  149. }
  150. /**
  151. * Creates an error object to be thrown when an argument did not use the supported value
  152. *
  153. * @public
  154. * @static
  155. * @param {string} message - Error message to be displayed.
  156. * @param {string} argument - Argument name.
  157. * @param {string} value - Argument value.
  158. * @param {string} [reason] - Why value is invalid.
  159. * @returns {Error} instance detailing the error condition
  160. */
  161. function createInvalidArgumentValueError(message, argument, value, reason) {
  162. var err = new TypeError(message);
  163. err.code = constants.INVALID_ARG_VALUE;
  164. err.argument = argument;
  165. err.value = value;
  166. err.reason = typeof reason !== 'undefined' ? reason : 'is invalid';
  167. return err;
  168. }
  169. /**
  170. * Creates an error object to be thrown when an exception was caught, but the `Error` is falsy or undefined.
  171. *
  172. * @public
  173. * @static
  174. * @param {string} message - Error message to be displayed.
  175. * @returns {Error} instance detailing the error condition
  176. */
  177. function createInvalidExceptionError(message, value) {
  178. var err = new Error(message);
  179. err.code = constants.INVALID_EXCEPTION;
  180. err.valueType = typeof value;
  181. err.value = value;
  182. return err;
  183. }
  184. /**
  185. * Creates an error object to be thrown when an unrecoverable error occurs.
  186. *
  187. * @public
  188. * @static
  189. * @param {string} message - Error message to be displayed.
  190. * @returns {Error} instance detailing the error condition
  191. */
  192. function createFatalError(message, value) {
  193. var err = new Error(message);
  194. err.code = constants.FATAL;
  195. err.valueType = typeof value;
  196. err.value = value;
  197. return err;
  198. }
  199. /**
  200. * Dynamically creates a plugin-type-specific error based on plugin type
  201. * @param {string} message - Error message
  202. * @param {"reporter"|"ui"} pluginType - Plugin type. Future: expand as needed
  203. * @param {string} [pluginId] - Name/path of plugin, if any
  204. * @throws When `pluginType` is not known
  205. * @public
  206. * @static
  207. * @returns {Error}
  208. */
  209. function createInvalidLegacyPluginError(message, pluginType, pluginId) {
  210. switch (pluginType) {
  211. case 'reporter':
  212. return createInvalidReporterError(message, pluginId);
  213. case 'ui':
  214. return createInvalidInterfaceError(message, pluginId);
  215. default:
  216. throw new Error('unknown pluginType "' + pluginType + '"');
  217. }
  218. }
  219. /**
  220. * **DEPRECATED**. Use {@link createInvalidLegacyPluginError} instead Dynamically creates a plugin-type-specific error based on plugin type
  221. * @deprecated
  222. * @param {string} message - Error message
  223. * @param {"reporter"|"interface"} pluginType - Plugin type. Future: expand as needed
  224. * @param {string} [pluginId] - Name/path of plugin, if any
  225. * @throws When `pluginType` is not known
  226. * @public
  227. * @static
  228. * @returns {Error}
  229. */
  230. function createInvalidPluginError(...args) {
  231. deprecate('Use createInvalidLegacyPluginError() instead');
  232. return createInvalidLegacyPluginError(...args);
  233. }
  234. /**
  235. * Creates an error object to be thrown when a mocha object's `run` method is executed while it is already disposed.
  236. * @param {string} message The error message to be displayed.
  237. * @param {boolean} cleanReferencesAfterRun the value of `cleanReferencesAfterRun`
  238. * @param {Mocha} instance the mocha instance that throw this error
  239. * @static
  240. */
  241. function createMochaInstanceAlreadyDisposedError(
  242. message,
  243. cleanReferencesAfterRun,
  244. instance
  245. ) {
  246. var err = new Error(message);
  247. err.code = constants.INSTANCE_ALREADY_DISPOSED;
  248. err.cleanReferencesAfterRun = cleanReferencesAfterRun;
  249. err.instance = instance;
  250. return err;
  251. }
  252. /**
  253. * Creates an error object to be thrown when a mocha object's `run` method is called while a test run is in progress.
  254. * @param {string} message The error message to be displayed.
  255. * @static
  256. * @public
  257. */
  258. function createMochaInstanceAlreadyRunningError(message, instance) {
  259. var err = new Error(message);
  260. err.code = constants.INSTANCE_ALREADY_RUNNING;
  261. err.instance = instance;
  262. return err;
  263. }
  264. /**
  265. * Creates an error object to be thrown when done() is called multiple times in a test
  266. *
  267. * @public
  268. * @param {Runnable} runnable - Original runnable
  269. * @param {Error} [originalErr] - Original error, if any
  270. * @returns {Error} instance detailing the error condition
  271. * @static
  272. */
  273. function createMultipleDoneError(runnable, originalErr) {
  274. var title;
  275. try {
  276. title = format('<%s>', runnable.fullTitle());
  277. if (runnable.parent.root) {
  278. title += ' (of root suite)';
  279. }
  280. } catch (ignored) {
  281. title = format('<%s> (of unknown suite)', runnable.title);
  282. }
  283. var message = format(
  284. 'done() called multiple times in %s %s',
  285. runnable.type ? runnable.type : 'unknown runnable',
  286. title
  287. );
  288. if (runnable.file) {
  289. message += format(' of file %s', runnable.file);
  290. }
  291. if (originalErr) {
  292. message += format('; in addition, done() received error: %s', originalErr);
  293. }
  294. var err = new Error(message);
  295. err.code = constants.MULTIPLE_DONE;
  296. err.valueType = typeof originalErr;
  297. err.value = originalErr;
  298. return err;
  299. }
  300. /**
  301. * Creates an error object to be thrown when `.only()` is used with
  302. * `--forbid-only`.
  303. * @static
  304. * @public
  305. * @param {Mocha} mocha - Mocha instance
  306. * @returns {Error} Error with code {@link constants.FORBIDDEN_EXCLUSIVITY}
  307. */
  308. function createForbiddenExclusivityError(mocha) {
  309. var err = new Error(
  310. mocha.isWorker
  311. ? '`.only` is not supported in parallel mode'
  312. : '`.only` forbidden by --forbid-only'
  313. );
  314. err.code = constants.FORBIDDEN_EXCLUSIVITY;
  315. return err;
  316. }
  317. /**
  318. * Creates an error object to be thrown when a plugin definition is invalid
  319. * @static
  320. * @param {string} msg - Error message
  321. * @param {PluginDefinition} [pluginDef] - Problematic plugin definition
  322. * @public
  323. * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION}
  324. */
  325. function createInvalidPluginDefinitionError(msg, pluginDef) {
  326. const err = new Error(msg);
  327. err.code = constants.INVALID_PLUGIN_DEFINITION;
  328. err.pluginDef = pluginDef;
  329. return err;
  330. }
  331. /**
  332. * Creates an error object to be thrown when a plugin implementation (user code) is invalid
  333. * @static
  334. * @param {string} msg - Error message
  335. * @param {Object} [opts] - Plugin definition and user-supplied implementation
  336. * @param {PluginDefinition} [opts.pluginDef] - Plugin Definition
  337. * @param {*} [opts.pluginImpl] - Plugin Implementation (user-supplied)
  338. * @public
  339. * @returns {Error} Error with code {@link constants.INVALID_PLUGIN_DEFINITION}
  340. */
  341. function createInvalidPluginImplementationError(
  342. msg,
  343. {pluginDef, pluginImpl} = {}
  344. ) {
  345. const err = new Error(msg);
  346. err.code = constants.INVALID_PLUGIN_IMPLEMENTATION;
  347. err.pluginDef = pluginDef;
  348. err.pluginImpl = pluginImpl;
  349. return err;
  350. }
  351. /**
  352. * Creates an error object to be thrown when a runnable exceeds its allowed run time.
  353. * @static
  354. * @param {string} msg - Error message
  355. * @param {number} [timeout] - Timeout in ms
  356. * @param {string} [file] - File, if given
  357. * @returns {MochaTimeoutError}
  358. */
  359. function createTimeoutError(msg, timeout, file) {
  360. const err = new Error(msg);
  361. err.code = constants.TIMEOUT;
  362. err.timeout = timeout;
  363. err.file = file;
  364. return err;
  365. }
  366. /**
  367. * Creates an error object to be thrown when file is unparsable
  368. * @public
  369. * @static
  370. * @param {string} message - Error message to be displayed.
  371. * @returns {Error} Error with code {@link constants.UNPARSABLE_FILE}
  372. */
  373. function createUnparsableFileError(message) {
  374. var err = new Error(message);
  375. err.code = constants.UNPARSABLE_FILE;
  376. return err;
  377. }
  378. /**
  379. * Returns `true` if an error came out of Mocha.
  380. * _Can suffer from false negatives, but not false positives._
  381. * @static
  382. * @public
  383. * @param {*} err - Error, or anything
  384. * @returns {boolean}
  385. */
  386. const isMochaError = err =>
  387. Boolean(err && typeof err === 'object' && MOCHA_ERRORS.has(err.code));
  388. module.exports = {
  389. createFatalError,
  390. createForbiddenExclusivityError,
  391. createInvalidArgumentTypeError,
  392. createInvalidArgumentValueError,
  393. createInvalidExceptionError,
  394. createInvalidInterfaceError,
  395. createInvalidLegacyPluginError,
  396. createInvalidPluginDefinitionError,
  397. createInvalidPluginError,
  398. createInvalidPluginImplementationError,
  399. createInvalidReporterError,
  400. createMissingArgumentError,
  401. createMochaInstanceAlreadyDisposedError,
  402. createMochaInstanceAlreadyRunningError,
  403. createMultipleDoneError,
  404. createNoFilesMatchPatternError,
  405. createTimeoutError,
  406. createUnparsableFileError,
  407. createUnsupportedError,
  408. deprecate,
  409. isMochaError,
  410. warn
  411. };