From 4f4b27407ca27063aa1832b5f8803882b8a430bc Mon Sep 17 00:00:00 2001 From: pipopotamasu Date: Fri, 23 Feb 2024 12:19:03 +0900 Subject: [PATCH] add try catch finally pattern to return statement (#49) --- .../return-statement/index.spec.ts | 25 +++++++++++++++++++ .../no-implicit-any/return-statement/index.ts | 6 ++++- 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/rules/no-implicit-any/return-statement/index.spec.ts b/rules/no-implicit-any/return-statement/index.spec.ts index 3a4b0b2..d6852ef 100644 --- a/rules/no-implicit-any/return-statement/index.spec.ts +++ b/rules/no-implicit-any/return-statement/index.spec.ts @@ -99,6 +99,31 @@ ruleTester.run('return-statement', rule, { } `, }, + { + code: ` + function foo () { + try { + return doSomethingMightHaveError(); + } catch { + throw new Error('error'); + } finally { + return null; + } + } + `, + }, + { + code: ` + function foo () { + try { + doSomethingMightHaveError(); + return null; + } catch { + return 'error' + } + } + `, + }, ], invalid: [ { diff --git a/rules/no-implicit-any/return-statement/index.ts b/rules/no-implicit-any/return-statement/index.ts index 1a03cc7..7d4a99f 100644 --- a/rules/no-implicit-any/return-statement/index.ts +++ b/rules/no-implicit-any/return-statement/index.ts @@ -56,6 +56,11 @@ function getReturnStatementNodes(nodes: TSESTree.Statement[]) { returnStatementNodes.push(getReturnStatementNodes(caseNode.consequent)); }); break; + case AST_NODE_TYPES.TryStatement: + returnStatementNodes.push(getReturnStatementNodes(node.block.body)); + if (node.handler) returnStatementNodes.push(getReturnStatementNode(node.handler.body)); + if (node.finalizer) returnStatementNodes.push(getReturnStatementNodes(node.finalizer.body)); + break; case AST_NODE_TYPES.IfStatement: returnStatementNodes.push(getReturnStatementNode(node.consequent)); if (node.alternate) returnStatementNodes.push(getReturnStatementNode(node.alternate)); @@ -91,7 +96,6 @@ export const lintReturnStatement = ( const functionNode = getFunctionNode(node.parent); if (functionNode.body.type !== AST_NODE_TYPES.BlockStatement) return; const returnStatementNodes = getReturnStatementNodes(functionNode.body.body); - let shouldReport = true; for (const returnStatementNode of returnStatementNodes) {