Skip to content

Commit

Permalink
SwallowedException: fix false positive when exception is used as a re…
Browse files Browse the repository at this point in the history
…ceiver (#7288)
  • Loading branch information
t-kameyama committed May 12, 2024
1 parent b553d95 commit 5746604
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 5 deletions.
Expand Up @@ -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<KtThrowExpression> { throwExpr ->
val parameterReferences = throwExpr.parameterReferences(parameterName, catchBody)
parameterReferences.isNotEmpty() && parameterReferences.all { it is KtDotQualifiedExpression }
} == true
val catchBody = catchClause.catchBody ?: return false
return catchBody.anyDescendantOfType<KtThrowExpression> { throwExpr ->
val refs = throwExpr.parameterReferences(parameterName, catchBody)
refs.isNotEmpty() && refs.all { it is KtDotQualifiedExpression && it.parent !is KtThrowExpression }
}
}

private fun KtThrowExpression.parameterReferences(
Expand Down
Expand Up @@ -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) {
Expand Down

0 comments on commit 5746604

Please sign in to comment.