Can some one help me why SonarLint is showing this:
Either log this exception and handle it, or rethrow it with some contextual information.
for below piece of code.
public static <T> T getObjectFromJson(final Object jsonString, final Class<T> valueType) {
T object = null;
if (jsonString != null) {
try {
object = MAPPER.readValue(jsonString.toString(), valueType);
} catch (IOException io) {
log.error(ERROR_LOG_STR + " in method getObjectFromJson(). Exception Message={}, Exception Stack ={}",
io.getMessage(), io);
throw new ServiceException(ErrorMessages.JSON_SERIALIZATION_ERROR, io.getCause());
}
}
return object;
}

It's about the either ... or, see Sonar's Rule spec RSPEC-2139:
Exceptions should be either logged or rethrown but not both
To be compliant with the rule, decide for one:
try {
object = MAPPER.readValue(jsonString.toString(), valueType);
} catch (IOException io) {
log.error(ERROR_LOG_STR + " in method getObjectFromJson(). Exception Message={}, Exception Stack ={}",
io.getMessage(), io);
}
try {
object = MAPPER.readValue(jsonString.toString(), valueType);
} catch (IOException io) {
throw new ServiceException(ErrorMessages.JSON_SERIALIZATION_ERROR, io); // would use the full exception, not only the wrapped .getCause()
}
You can log additionally in a global or local error-handling interceptor like Spring's @ControllerAdvice annotated error-handler.
Most loggers allow to pass a Throwable when logging at error-level.
For example using Slf4j: log.error(ERROR_LOG_STR + " in method getObjectFromJson(): " + io.getMessage(), io)
See also:
RSPEC-1166: Exception handlers should preserve the original exceptions
The spec feature was resolved 2018-11-02 with version 5.9, implementation for Java fixed 2019-02-15 with version 5.11.
⚠️ Partial fix only: The marked duplicate and obourgain's answer do not solve the two-fold case here completely:
Similar questions coping with RSPEC-1166:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With