preserve-caught-error.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  1. /**
  2. * @fileoverview Rule to preserve caught errors when re-throwing exceptions
  3. * @author Amnish Singh Arora
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("./utils/ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Types
  12. //------------------------------------------------------------------------------
  13. /** @typedef {import("estree").Node} ASTNode */
  14. //------------------------------------------------------------------------------
  15. // Helpers
  16. //------------------------------------------------------------------------------
  17. /*
  18. * This is an indicator of an error cause node, that is too complicated to be detected and fixed.
  19. * Eg, when error options is an `Identifier` or a `SpreadElement`.
  20. */
  21. const UNKNOWN_CAUSE = Symbol("unknown_cause");
  22. const BUILT_IN_ERROR_TYPES = new Set([
  23. "Error",
  24. "EvalError",
  25. "RangeError",
  26. "ReferenceError",
  27. "SyntaxError",
  28. "TypeError",
  29. "URIError",
  30. "AggregateError",
  31. ]);
  32. /**
  33. * Finds and returns information about the `cause` property of an error being thrown.
  34. * @param {ASTNode} throwStatement `ThrowStatement` to be checked.
  35. * @returns {{ value: ASTNode; multipleDefinitions: boolean; } | UNKNOWN_CAUSE | null}
  36. * Information about the `cause` of the error being thrown, such as the value node and
  37. * whether there are multiple definitions of `cause`. `null` if there is no `cause`.
  38. */
  39. function getErrorCause(throwStatement) {
  40. const throwExpression = throwStatement.argument;
  41. /*
  42. * Determine which argument index holds the options object
  43. * `AggregateError` is a special case as it accepts the `options` object as third argument.
  44. */
  45. const optionsIndex =
  46. throwExpression.callee.name === "AggregateError" ? 2 : 1;
  47. /*
  48. * Make sure there is no `SpreadElement` at or before the `optionsIndex`
  49. * as this messes up the effective order of arguments and makes it complicated
  50. * to track where the actual error options need to be at
  51. */
  52. const spreadExpressionIndex = throwExpression.arguments.findIndex(
  53. arg => arg.type === "SpreadElement",
  54. );
  55. if (spreadExpressionIndex >= 0 && spreadExpressionIndex <= optionsIndex) {
  56. return UNKNOWN_CAUSE;
  57. }
  58. const errorOptions = throwExpression.arguments[optionsIndex];
  59. if (errorOptions) {
  60. if (errorOptions.type === "ObjectExpression") {
  61. if (
  62. errorOptions.properties.some(
  63. prop => prop.type === "SpreadElement",
  64. )
  65. ) {
  66. /*
  67. * If there is a spread element as part of error options, it is too complicated
  68. * to verify if the cause is used properly and auto-fix.
  69. */
  70. return UNKNOWN_CAUSE;
  71. }
  72. const causeProperties = errorOptions.properties.filter(
  73. prop => astUtils.getStaticPropertyName(prop) === "cause",
  74. );
  75. const causeProperty = causeProperties.at(-1);
  76. return causeProperty
  77. ? {
  78. value: causeProperty.value,
  79. multipleDefinitions: causeProperties.length > 1,
  80. }
  81. : null;
  82. }
  83. // Error options exist, but too complicated to be analyzed/fixed
  84. return UNKNOWN_CAUSE;
  85. }
  86. return null;
  87. }
  88. /**
  89. * Finds and returns the `CatchClause` node, that the `node` is part of.
  90. * @param {ASTNode} node The AST node to be evaluated.
  91. * @returns {ASTNode | null } The closest parent `CatchClause` node, `null` if the `node` is not in a catch block.
  92. */
  93. function findParentCatch(node) {
  94. let currentNode = node;
  95. while (currentNode && currentNode.type !== "CatchClause") {
  96. if (
  97. [
  98. "FunctionDeclaration",
  99. "FunctionExpression",
  100. "ArrowFunctionExpression",
  101. "StaticBlock",
  102. ].includes(currentNode.type)
  103. ) {
  104. /*
  105. * Make sure the ThrowStatement is not made inside a function definition or a static block inside a high level catch.
  106. * In such cases, the caught error is not directly related to the Throw.
  107. *
  108. * For example,
  109. * try {
  110. * } catch (error) {
  111. * foo = {
  112. * bar() {
  113. * throw new Error();
  114. * }
  115. * };
  116. * }
  117. */
  118. return null;
  119. }
  120. currentNode = currentNode.parent;
  121. }
  122. return currentNode;
  123. }
  124. //------------------------------------------------------------------------------
  125. // Rule Definition
  126. //------------------------------------------------------------------------------
  127. /** @type {import('../types').Rule.RuleModule} */
  128. module.exports = {
  129. meta: {
  130. type: "suggestion",
  131. defaultOptions: [
  132. {
  133. requireCatchParameter: false,
  134. },
  135. ],
  136. docs: {
  137. description:
  138. "Disallow losing originally caught error when re-throwing custom errors",
  139. recommended: false,
  140. url: "https://eslint.org/docs/latest/rules/preserve-caught-error", // URL to the documentation page for this rule
  141. },
  142. /*
  143. * TODO: We should allow passing `customErrorTypes` option once something like `typescript-eslint`'s
  144. * `TypeOrValueSpecifier` is implemented in core Eslint.
  145. * See:
  146. * 1. https://typescript-eslint.io/packages/type-utils/type-or-value-specifier/
  147. * 2. https://github.com/eslint/eslint/pull/19913#discussion_r2192608593
  148. * 3. https://github.com/eslint/eslint/discussions/16540
  149. */
  150. schema: [
  151. {
  152. type: "object",
  153. properties: {
  154. requireCatchParameter: {
  155. type: "boolean",
  156. description:
  157. "Requires the catch blocks to always have the caught error parameter so it is not discarded.",
  158. },
  159. },
  160. additionalProperties: false,
  161. },
  162. ],
  163. messages: {
  164. missingCause:
  165. "There is no `cause` attached to the symptom error being thrown.",
  166. incorrectCause:
  167. "The symptom error is being thrown with an incorrect `cause`.",
  168. includeCause:
  169. "Include the original caught error as the `cause` of the symptom error.",
  170. missingCatchErrorParam:
  171. "The caught error is not accessible because the catch clause lacks the error parameter. Start referencing the caught error using the catch parameter.",
  172. partiallyLostError:
  173. "Re-throws cannot preserve the caught error as a part of it is being lost due to destructuring.",
  174. caughtErrorShadowed:
  175. "The caught error is being attached as `cause`, but is shadowed by a closer scoped redeclaration.",
  176. },
  177. hasSuggestions: true,
  178. },
  179. create(context) {
  180. const sourceCode = context.sourceCode;
  181. const [{ requireCatchParameter }] = context.options;
  182. //----------------------------------------------------------------------
  183. // Helpers
  184. //----------------------------------------------------------------------
  185. /**
  186. * Checks if a `ThrowStatement` is constructing and throwing a new `Error` object.
  187. *
  188. * Covers all the error types on `globalThis` that support `cause` property:
  189. * https://github.com/microsoft/TypeScript/blob/main/src/lib/es2022.error.d.ts
  190. * @param {ASTNode} throwStatement The `ThrowStatement` that needs to be checked.
  191. * @returns {boolean} `true` if a new "Error" is being thrown, else `false`.
  192. */
  193. function isThrowingNewError(throwStatement) {
  194. return (
  195. (throwStatement.argument.type === "NewExpression" ||
  196. throwStatement.argument.type === "CallExpression") &&
  197. throwStatement.argument.callee.type === "Identifier" &&
  198. BUILT_IN_ERROR_TYPES.has(throwStatement.argument.callee.name) &&
  199. /*
  200. * Make sure the thrown Error is instance is one of the built-in global error types.
  201. * Custom imports could shadow this, which would lead to false positives.
  202. * e.g. import { Error } from "./my-custom-error.js";
  203. * throw Error("Failed to perform error prone operations");
  204. */
  205. sourceCode.isGlobalReference(throwStatement.argument.callee)
  206. );
  207. }
  208. /**
  209. * Inserts `cause: <caughtErrorName>` into an inline options object expression.
  210. * @param {RuleFixer} fixer The fixer object.
  211. * @param {ASTNode} optionsNode The options object node.
  212. * @param {string} caughtErrorName The name of the caught error (e.g., "err").
  213. * @returns {Fix} The fix object.
  214. */
  215. function insertCauseIntoOptions(fixer, optionsNode, caughtErrorName) {
  216. const properties = optionsNode.properties;
  217. if (properties.length === 0) {
  218. // Insert inside empty braces: `{}` → `{ cause: err }`
  219. return fixer.insertTextAfter(
  220. sourceCode.getFirstToken(optionsNode),
  221. `cause: ${caughtErrorName}`,
  222. );
  223. }
  224. const lastProp = properties.at(-1);
  225. return fixer.insertTextAfter(
  226. lastProp,
  227. `, cause: ${caughtErrorName}`,
  228. );
  229. }
  230. //----------------------------------------------------------------------
  231. // Public
  232. //----------------------------------------------------------------------
  233. return {
  234. ThrowStatement(node) {
  235. // Check if the throw is inside a catch block
  236. const parentCatch = findParentCatch(node);
  237. const throwStatement = node;
  238. // Check if a new error is being thrown in a catch block
  239. if (parentCatch && isThrowingNewError(throwStatement)) {
  240. if (
  241. parentCatch.param &&
  242. parentCatch.param.type !== "Identifier"
  243. ) {
  244. /*
  245. * When a part of the caught error is being lost at the parameter level, commonly due to destructuring.
  246. * e.g. catch({ message, ...rest })
  247. */
  248. context.report({
  249. messageId: "partiallyLostError",
  250. node: parentCatch,
  251. });
  252. return;
  253. }
  254. const caughtError =
  255. parentCatch.param?.type === "Identifier"
  256. ? parentCatch.param
  257. : null;
  258. // Check if there are throw statements and caught error is being ignored
  259. if (!caughtError) {
  260. if (requireCatchParameter) {
  261. context.report({
  262. node: throwStatement,
  263. messageId: "missingCatchErrorParam",
  264. });
  265. return;
  266. }
  267. return;
  268. }
  269. // Check if there is a cause attached to the new error
  270. const errorCauseInfo = getErrorCause(throwStatement);
  271. if (errorCauseInfo === UNKNOWN_CAUSE) {
  272. // Error options exist, but too complicated to be analyzed/fixed
  273. return;
  274. }
  275. if (errorCauseInfo === null) {
  276. // If there is no `cause` attached to the error being thrown.
  277. context.report({
  278. messageId: "missingCause",
  279. node: throwStatement,
  280. suggest: [
  281. {
  282. messageId: "includeCause",
  283. fix(fixer) {
  284. const throwExpression =
  285. throwStatement.argument;
  286. const args = throwExpression.arguments;
  287. const errorType =
  288. throwExpression.callee.name;
  289. // AggregateError: errors, message, options
  290. if (errorType === "AggregateError") {
  291. const errorsArg = args[0];
  292. const messageArg = args[1];
  293. const optionsArg = args[2];
  294. if (!errorsArg) {
  295. // Case: `throw new AggregateError()` → insert all arguments
  296. const lastToken =
  297. sourceCode.getLastToken(
  298. throwExpression,
  299. );
  300. const lastCalleeToken =
  301. sourceCode.getLastToken(
  302. throwExpression.callee,
  303. );
  304. const parenToken =
  305. sourceCode.getFirstTokenBetween(
  306. lastCalleeToken,
  307. lastToken,
  308. astUtils.isOpeningParenToken,
  309. );
  310. if (parenToken) {
  311. return fixer.insertTextAfter(
  312. parenToken,
  313. `[], "", { cause: ${caughtError.name} }`,
  314. );
  315. }
  316. return fixer.insertTextAfter(
  317. throwExpression.callee,
  318. `([], "", { cause: ${caughtError.name} })`,
  319. );
  320. }
  321. if (!messageArg) {
  322. // Case: `throw new AggregateError([])` → insert message and options
  323. return fixer.insertTextAfter(
  324. errorsArg,
  325. `, "", { cause: ${caughtError.name} }`,
  326. );
  327. }
  328. if (!optionsArg) {
  329. // Case: `throw new AggregateError([], "")` → insert error options only
  330. return fixer.insertTextAfter(
  331. messageArg,
  332. `, { cause: ${caughtError.name} }`,
  333. );
  334. }
  335. if (
  336. optionsArg.type ===
  337. "ObjectExpression"
  338. ) {
  339. return insertCauseIntoOptions(
  340. fixer,
  341. optionsArg,
  342. caughtError.name,
  343. );
  344. }
  345. // Complex dynamic options — skip
  346. return null;
  347. }
  348. // Normal Error types
  349. const messageArg = args[0];
  350. const optionsArg = args[1];
  351. if (!messageArg) {
  352. // Case: `throw new Error()` → insert both message and options
  353. const lastToken =
  354. sourceCode.getLastToken(
  355. throwExpression,
  356. );
  357. const lastCalleeToken =
  358. sourceCode.getLastToken(
  359. throwExpression.callee,
  360. );
  361. const parenToken =
  362. sourceCode.getFirstTokenBetween(
  363. lastCalleeToken,
  364. lastToken,
  365. astUtils.isOpeningParenToken,
  366. );
  367. if (parenToken) {
  368. return fixer.insertTextAfter(
  369. parenToken,
  370. `"", { cause: ${caughtError.name} }`,
  371. );
  372. }
  373. return fixer.insertTextAfter(
  374. throwExpression.callee,
  375. `("", { cause: ${caughtError.name} })`,
  376. );
  377. }
  378. if (!optionsArg) {
  379. // Case: `throw new Error("Some message")` → insert only options
  380. return fixer.insertTextAfter(
  381. messageArg,
  382. `, { cause: ${caughtError.name} }`,
  383. );
  384. }
  385. if (
  386. optionsArg.type ===
  387. "ObjectExpression"
  388. ) {
  389. return insertCauseIntoOptions(
  390. fixer,
  391. optionsArg,
  392. caughtError.name,
  393. );
  394. }
  395. return null; // Identifier or spread — do not fix
  396. },
  397. },
  398. ],
  399. });
  400. // We don't need to check further
  401. return;
  402. }
  403. const { value: thrownErrorCause } = errorCauseInfo;
  404. // If there is an attached cause, verify that it matches the caught error
  405. if (
  406. !(
  407. thrownErrorCause.type === "Identifier" &&
  408. thrownErrorCause.name === caughtError.name
  409. )
  410. ) {
  411. const suggest = errorCauseInfo.multipleDefinitions
  412. ? null // If there are multiple `cause` definitions, a suggestion could be confusing.
  413. : [
  414. {
  415. messageId: "includeCause",
  416. fix(fixer) {
  417. /*
  418. * In case `cause` is attached using object property shorthand or as a method or accessor.
  419. * e.g. throw Error("fail", { cause });
  420. * throw Error("fail", { cause() { doSomething(); } });
  421. * throw Error("fail", { get cause() { return error; } });
  422. */
  423. if (
  424. thrownErrorCause.parent
  425. .method ||
  426. thrownErrorCause.parent
  427. .shorthand ||
  428. thrownErrorCause.parent.kind !==
  429. "init"
  430. ) {
  431. return fixer.replaceText(
  432. thrownErrorCause.parent,
  433. `cause: ${caughtError.name}`,
  434. );
  435. }
  436. return fixer.replaceText(
  437. thrownErrorCause,
  438. caughtError.name,
  439. );
  440. },
  441. },
  442. ];
  443. context.report({
  444. messageId: "incorrectCause",
  445. node: thrownErrorCause,
  446. suggest,
  447. });
  448. return;
  449. }
  450. /*
  451. * If the attached cause matches the identifier name of the caught error,
  452. * make sure it is not being shadowed by a closer scoped redeclaration.
  453. *
  454. * e.g. try {
  455. * doSomething();
  456. * } catch (error) {
  457. * if (whatever) {
  458. * const error = anotherError;
  459. * throw new Error("Something went wrong");
  460. * }
  461. * }
  462. */
  463. let scope = sourceCode.getScope(throwStatement);
  464. do {
  465. const variable = scope.set.get(caughtError.name);
  466. if (variable) {
  467. break;
  468. }
  469. scope = scope.upper;
  470. } while (scope);
  471. if (scope?.block !== parentCatch) {
  472. // Caught error is being shadowed
  473. context.report({
  474. messageId: "caughtErrorShadowed",
  475. node: throwStatement,
  476. });
  477. }
  478. }
  479. },
  480. };
  481. },
  482. };