How to fix Sonar Violation: Invoke methods only conditionally and Either Log or rethrow the exception

Viewed 472

I have the below statements in my code which violates some Sonar Rules.

LOG.info("Fetched: {}", mapper.writeValueAsString(requests));

This one shows Invoke method(s) only conditionally for mapper.writeValueAsString(requests).

}catch (Exception e) {
            LOG.error("Exception occurred while trying to fetch requests", e);
            throw new GenericException(Error.FETCH_REQUEST_ERR_001.name(), e.getMessage(), Error.FETCH_REQUEST_ERR_001.value());
        }

This one shows Either log this exception and handle it, or rethrow it with some contextual information. rule violation.

Any idea on how to resolve these. Appreciate any help.

1 Answers

I use IntelliJ and in a similar situation as yours SonarLint plugin accepted the following fix for me:

if(LOG.isInfoEnabled() && mapper != null){
 LOG.info("Fetched: {}", mapper.writeValueAsString(requests)); // Your code
}
Related