Skip to content

Commit b72090f

Browse files
committed
enhance CatchThrowable rule to allow catching Throwable with custom extractors and update corresponding tests
1 parent 4975fda commit b72090f

File tree

2 files changed

+13
-14
lines changed

2 files changed

+13
-14
lines changed

analyzer/src/main/scala/com/avsystem/commons/analyzer/CatchThrowable.scala

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -2,27 +2,19 @@ package com.avsystem.commons
22
package analyzer
33

44
import scala.tools.nsc.Global
5-
import scala.util.control.NonFatal
65

76
class CatchThrowable(g: Global) extends AnalyzerRule(g, "catchThrowable", Level.Warn) {
87

9-
import global._
8+
import global.*
109

1110
private lazy val throwableTpe = typeOf[Throwable]
1211

13-
private lazy val nonFatalSymbols = {
14-
val nonFatal = typeOf[NonFatal.type].termSymbol
15-
val nonFatalAlias = classType("com.avsystem.commons.CommonAliases").member(TermName("NonFatal"))
16-
17-
Set(nonFatal, nonFatalAlias)
18-
}
19-
20-
private def isNonFatalPattern(tree: Tree): Boolean = tree match {
21-
case UnApply(Apply(Select(qualifier, TermName("unapply")), _), _) if nonFatalSymbols contains qualifier.symbol => true
12+
private def isCustomExtractor(tree: Tree): Boolean = tree match {
13+
case UnApply(Apply(Select(_, TermName("unapply")), _), _) => true
2214
case _ => false
2315
}
2416

25-
private def checkTree(pat: Tree): Unit = if (pat.tpe != null && pat.tpe =:= throwableTpe && !isNonFatalPattern(pat)) {
17+
private def checkTree(pat: Tree): Unit = if (pat.tpe != null && pat.tpe =:= throwableTpe && !isCustomExtractor(pat)) {
2618
report(pat.pos, "Catching Throwable is discouraged, catch specific exceptions instead")
2719
}
2820

analyzer/src/test/scala/com/avsystem/commons/analyzer/CatchThrowableTest.scala

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,15 +73,22 @@ class CatchThrowableTest extends AnyFunSuite with AnalyzerTest {
7373
""".stripMargin)
7474
}
7575

76-
test("catching Throwable using NonFatal should be allowed") {
76+
test("catching Throwable using custom extractor should be allowed") {
7777
assertNoErrors(
7878
//language=Scala
7979
"""
80-
|object Test extends com.avsystem.commons.CommonAliases {
80+
|object Test extends com.avsystem.commons.CommonAliases {
81+
| object custom {
82+
| def unapply(t: Throwable): Option[IllegalArgumentException] = t match {
83+
| case e: IllegalArgumentException => Some(e)
84+
| case _ => None
85+
| }
86+
| }
8187
| def test(): Unit = {
8288
| try {
8389
| println("test")
8490
| } catch {
91+
| case custom(t) => println(t)
8592
| case NonFatal(t) => println(t)
8693
| case scala.util.control.NonFatal(t) => println(t)
8794
| }

0 commit comments

Comments
 (0)