Home > OS >  Either log this exception and handle it, or rethrow it with some contextual information
Either log this exception and handle it, or rethrow it with some contextual information

Time:01-06

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;
    }

enter image description here

CodePudding user response:

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:

  1. either log only:
            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);
            }
  1. or throw only:
           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()
           }

Bonus: How to achieve both and simplify

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:

CodePudding user response:

Sonar suggest you to use the full exception instead of the exception mesage in the rethrow.

Replace:

throw new ServiceException(ErrorMessages.JSON_SERIALIZATION_ERROR, io.getCause());

by:

throw new ServiceException(ErrorMessages.JSON_SERIALIZATION_ERROR, io);

  •  Tags:  
  • Related