javasonarqubesonarqube-4.5

Why does squid:S1166 not accept exception messages only when logging caught exceptions?


Quote from the description of the rule (SonarQube 4.5.5):

// Noncompliant - exception is lost (only message is preserved)   
try { /* ... */ } 
catch (Exception e) { LOGGER.info(e.getMessage()); }

By providing the exception class to the logger a stack trace is written to the logs.

The problem in our code base is this: By following the Tell, don't ask principle, we use checked exceptions as part of the, what we consider, normal execution paths and we don't want them to result in unreasonably large log messages.

A few examples: Servers responding with error codes, database statement executions failing on optimistic locking (concurrent users)...

My suggestion: Split this case in two.

// Noncompliant - exception is lost (only message is preserved)
try { /* ... */ } 
catch (Exception e) { LOGGER.info(e.getMessage()); } 

and

// Compliant - exception is lost (only message is preserved) but there is business logic handling the situation      

try { 
/* ... */  
} catch (Exception e) {   
   LOGGER.info(e.getMessage());  
   */ exception handling  */  
}

The rule squid:S00108 (code blocks must not be empty) would not catch the problem since there is a logging statement.

Is this not reasonable? Have I missed something of importance?

Note: I've rewritten the question to clarify my use case


Solution

  • I understand the arguments for maintaining the stack trace and all that, but I think it's going to bloat your logs for a < ERROR level event. One solution is to log the message as a WARN and log the exception object as DEBUG or TRACE. That way a normal user log config would not be flooded with business as usual stack traces, but it would still be possible to get a stack trace if necessary.