From b3715f9c71a593da03059aafd4dc9554bfa4a65c Mon Sep 17 00:00:00 2001 From: Toshiaki Kameyama Date: Sat, 11 May 2024 13:01:17 +0900 Subject: [PATCH] SwallowedException: fix false positive when exception is used as a receiver --- .../rules/exceptions/SwallowedException.kt | 10 +++++----- .../rules/exceptions/SwallowedExceptionSpec.kt | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/detekt-rules-exceptions/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/SwallowedException.kt b/detekt-rules-exceptions/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/SwallowedException.kt index 0e9eabfb27b..bb402e3f9c7 100644 --- a/detekt-rules-exceptions/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/SwallowedException.kt +++ b/detekt-rules-exceptions/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/SwallowedException.kt @@ -105,11 +105,11 @@ class SwallowedException(config: Config) : Rule( private fun isExceptionSwallowed(catchClause: KtCatchClause): Boolean { val parameterName = catchClause.catchParameter?.name - val catchBody = catchClause.catchBody - return catchBody?.anyDescendantOfType { throwExpr -> - val parameterReferences = throwExpr.parameterReferences(parameterName, catchBody) - parameterReferences.isNotEmpty() && parameterReferences.all { it is KtDotQualifiedExpression } - } == true + val catchBody = catchClause.catchBody ?: return false + return catchBody.anyDescendantOfType { throwExpr -> + val refs = throwExpr.parameterReferences(parameterName, catchBody) + refs.isNotEmpty() && refs.all { it is KtDotQualifiedExpression && it.parent !is KtThrowExpression } + } } private fun KtThrowExpression.parameterReferences( diff --git a/detekt-rules-exceptions/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/SwallowedExceptionSpec.kt b/detekt-rules-exceptions/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/SwallowedExceptionSpec.kt index 78f29479e28..62d6ce7bc24 100644 --- a/detekt-rules-exceptions/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/SwallowedExceptionSpec.kt +++ b/detekt-rules-exceptions/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/exceptions/SwallowedExceptionSpec.kt @@ -266,6 +266,23 @@ class SwallowedExceptionSpec { assertThat(subject.compileAndLint(code)).isEmpty() } + @Test + fun `does not report when an exception is used as a receiver and the return value is thrown`() { + val code = """ + fun Exception.transformException(): Exception { + return this + } + + fun test() { + try { + } catch (e: Exception) { + throw e.transformException() + } + } + """.trimIndent() + assertThat(subject.compileAndLint(code)).isEmpty() + } + @ParameterizedTest(name = "ignores {0} in the catch clause by default") @MethodSource("io.gitlab.arturbosch.detekt.rules.exceptions.SwallowedException#getEXCEPTIONS_IGNORED_BY_DEFAULT") fun `ignores $exceptionName in the catch clause by default`(exceptionName: String) {