SonarQube 抱怨:记录或重新抛出此异常

2022-01-17 00:00:00 exception sonarqube spring java

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

I am running SonarQube 5 for code quality check after integrating the code with Maven.

Sonar 抱怨我应该:

Sonar is complaining that I should:

记录或重新抛出此异常.

Either log or rethrow this exception.

在以下代码中:

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 似乎有点奇怪.

First of all, is this behaviour correct? Seems a bit weird that you are trying to call convertStringtoDate on the exception message as well.

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

Secondly, I had the same problem with Sonar recently. Seems like you need to pass the whole exception as a parameter to the logger, instead of e.getMessage() for Sonar to realize you are logging the exception.

试试这个:

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;    
}

相关文章