I have the following piece of code in my program and I am running SonarQube 5 for code quality check on it after integrating it with Maven.
However, Sonar is complaining that I should Either log or rethrow this exception.
What am I missing here? Am I not already logging the exception?
private boolean authenticate(User user) {
boolean validUser = false;
int validUserCount = 0;
try {
DataSource dataSource = (DataSource) getServletContext().getAttribute("dataSource");
validUserCount = new MasterDao(dataSource).getValidUserCount(user);
} catch (SQLException sqle) {
LOG.error("Exception while validating user credentials for user with username: " + user.getUsername() + " and pwd:" + user.getPwd());
LOG.error(sqle.getMessage());
}
if (validUserCount == 1) {
validUser = true;
}
return validUser;
}
What sonar is asking you to do, is to persist the entire exception object. You can use something like:
If you believe that SQLException can be safely ignored, then you can add it to the list of exceptions for squid:S1166 rule.
You should do it this way :
Sonar shouldn't bother you anymore
I stumbled across the same issue. I'm not 100% sure if I'm completely right at this point, but basically you should rethrow or log the complete Exception. Whereas
e.getMessage()
just gives you the detailed message but not the snapshot of the execution stack.From the Oracle docs (Throwable):
This means the solution provided by abarre works, because the whole exception object (sqle) is being passed to the logger.
Hope it helps. Cheers.