【问题标题】:SonarQube complains: Either log or rethrow this exceptionSonarQube 抱怨:记录或重新抛出此异常
【发布时间】:2017-01-17 14:20:03
【问题描述】:

在将代码与 Maven 集成后,我正在运行 SonarQube 5 进行代码质量检查。

Sonar 抱怨我应该:

记录或重新抛出此异常。

在以下代码中:

public static Date convertStringtoDate(String stringDate) {
    stringDate = StringUtils.trimToNull(stringDate);
    SimpleDateFormat dfm = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = null;

    if (stringDate != null) {
        try {
            date = dfm.parse(stringDate);
        } catch (Exception e) {
            logger.info("Cannot convert String to Date: ",convertStringtoDate(e.getMessage()));
        }
    }

    return date;    
}

我在这里错过了什么?

【问题讨论】:

  • 它会递归吗?尝试从记录器中删除 convertStringtoDate() 方法调用并仅保留字符串状态
  • 如果您想故意忽略此警告(例如,异常是您业务逻辑的一部分),您可以使用以下注释:@SuppressWarnings("squid:S1166") // 异常是过程的一部分,为了防止原木泛滥而故意避免使用。在旁注中,我很惊讶 Sonar 没有抱怨捕获 Exception 而不是它的一个实现。

标签: java spring exception sonarqube


【解决方案1】:

首先,这种行为是否正确?您还尝试在异常消息上调用 convertStringtoDate 似乎有点奇怪。

其次,我最近在使用 Sonar 时遇到了同样的问题。似乎您需要将整个异常作为参数传递给记录器,而不是 e.getMessage(),Sonar 才能意识到您正在记录异常。

试试这个:

public static Date convertStringtoDate(String stringDate){
    stringDate = StringUtils.trimToNull(stringDate);
    SimpleDateFormat dfm = new SimpleDateFormat("dd-MMM-yyyy");
    Date date = null;
    if(stringDate!=null){
        try {
            date = dfm.parse(stringDate);
        } catch (Exception e) {
            logger.info("Cannot convert String to Date: ", e);
        }
    }
    return date;    
}

【讨论】:

  • 没错!该规则的部分要点是规则是不要丢失异常的上下文,当您只记录消息时会这样做。
猜你喜欢
  • 2022-01-12
  • 2015-03-23
  • 2015-11-18
  • 2015-10-26
  • 2012-02-21
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
相关资源
最近更新 更多