debugjavaspringMinor
Logging a message and the stack trace of caught exceptions
Viewed 0 times
loggingexceptionsthestackmessagecaughtandtrace
Problem
Using Spring's JdbcTemplate to load a specific object by ID if exists, I have this code:
A Sonar rule (squid:S1166) complains about this piece of code, basically saying that logging a message is not enough, I should also log the exception. But in this case, I don't see the point. Adding the exception as a 2nd parameter to the logger will put a completely pointless stack trace in my logs that doesn't contain anything that I don't already know.
Would you agree that this is a false positive or am I missing something? Or is there another way of writing this code that complies better with Sonar or code quality analysis tools in general?
Person person = null;
try {
person = jdbcTemplate.queryForObject(sql, new Object[]{ id }, new PersonMapper());
} catch (EmptyResultDataAccessException e) {
LOGGER.warn("Could not find person with id " + id);
}A Sonar rule (squid:S1166) complains about this piece of code, basically saying that logging a message is not enough, I should also log the exception. But in this case, I don't see the point. Adding the exception as a 2nd parameter to the logger will put a completely pointless stack trace in my logs that doesn't contain anything that I don't already know.
Would you agree that this is a false positive or am I missing something? Or is there another way of writing this code that complies better with Sonar or code quality analysis tools in general?
Solution
I agree it’s a false positive. Sonarqube is way too strict on this issue in my view and creates many false positives with that rule. Often, when catching a specific exception, we know exactly where it came from.
For this rule, I gave in and logged the exception on
For this rule, I gave in and logged the exception on
TRACE in addition to what I already logged at whatever different level. Sonarqube is satisfied, and the log stays clean unless you explicitly ask for verbose output.Context
StackExchange Code Review Q#56842, answer score: 5
Revisions (0)
No revisions yet.