2

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?

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Aawan
  • 453
  • 3
  • 6
  • 15
  • 1
    Is it going recursion ?? Try removing convertStringtoDate() method call from your logger and keep only string staement – Ravindra Devadiga Sep 09 '16 at 12:24
  • In case you wanted to ignore this warning on purpose (e.g. an exception is part of your business logic), you can use the following annotation: @SuppressWarnings("squid:S1166") // The exception is part of the process and is avoided on purpose to prevent flooding logs. On a side note, I'm surprised that Sonar does not complain about catching Exception instead of one of its implementations. – Romano Apr 04 '18 at 19:43

1 Answers1

3

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