Aawan
Aawan

Reputation: 463

SonarQube complains: Either log or rethrow this exception

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

Sonar is complaining that I should:

Either log or rethrow this exception.

in following piece of code:

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

What am I missing here?

Upvotes: 2

Views: 12082

Answers (1)

Jose Ignacio Acin Pozo
Jose Ignacio Acin Pozo

Reputation: 882

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

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.

Try this instead:

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

Upvotes: 3

Related Questions