You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决SonarQube捕获通用Exception/Throwable的检查告警?

解决SonarQube捕获通用Throwable/Exception的告警问题

问题原因

SonarQube的规则S1181(捕获通用异常)默认禁止捕获Exception或Throwable这类通用类型,目的是避免开发者忽略特定异常的针对性处理。但你的场景是全局切面日志,需要捕获所有异常来记录上下文信息后重新抛出,属于合法的例外场景。

可行解决方案

1. 代码中添加SonarQube忽略注释

在捕获Throwable的代码上方,添加注释明确告知SonarQube忽略该规则检查,同时保留业务说明注释,让其他开发者理解代码意图:

修改后的Kotlin代码示例:

import mu.KotlinLogging
import org.aspectj.lang.ProceedingJoinPoint
import org.aspectj.lang.annotation.Around
import org.aspectj.lang.annotation.Aspect
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit

@Aspect
@Component
class LogExceptionAndTimeAspect {
  private val log = KotlinLogging.logger { }

  @Around("apiPackage()")
  fun logExecutionTimeAndExceptionDetails(joinPoint: ProceedingJoinPoint): Any {

    val signature = joinPoint.signature.toShortString()
    val methodArguments = joinPoint.args.joinToString { "${it.javaClass.simpleName}($it)" }
    log.debug("Start....")

    val start = System.currentTimeMillis()
    val result = try {
      joinPoint.proceed()
    } 
    // 全局切面需捕获所有异常以记录上下文日志,随后重新抛出,忽略SonarQube通用异常捕获告警
    // sonarignore: squid:S1181
    catch (throwable: Throwable) { 
      val exceptionDetails = throwable.stackTraceToString().replace(System.lineSeparator(), "")
      log.error {
        "Error that is searchable is $signature, parameters: [$methodArguments], exception is $exceptionDetails"
      }
      log.debug("End....")
      throw throwable
    }

    val duration = System.currentTimeMillis() - start
    val durationInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration)
    log.info {
      "Aspect: the method $signature, parameters: [$methodArguments], took around $durationInSeconds seconds"
    }
    log.debug("End....")
    return result
  }
}
  • 可以用// NOSONAR代替// sonarignore: squid:S1181,前者会忽略该行所有Sonar规则,后者仅忽略指定规则,更精准。

2. 在SonarQube项目配置中排除规则

如果不想在代码中添加注释,可在SonarQube的项目规则配置里,将LogExceptionAndTimeAspect类排除在S1181规则的检查范围之外:

  • 进入SonarQube项目的「质量配置」页面
  • 找到规则S1181 - Caught exception is too generic
  • 点击「编辑」,在「排除项」中添加类的全限定名(替换成你的实际包名,比如com.yourcompany.LogExceptionAndTimeAspect)

3. 调整规则全局参数(不推荐)

如果你的SonarQube版本支持,也可以调整S1181规则的参数,将全局切面这类场景设为允许,但这种方式会放宽整个项目的规则限制,不如前两种方案精准。


内容的提问来源于stack exchange,提问作者firstpostcommenter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 06:10:06