Home > Blockchain >  SonarQube error in catch block in JsonProcessingException
SonarQube error in catch block in JsonProcessingException

Time:10-16

I have below code. we are using sonar 8.9 version and jdk 11. SonarQube always throw an critical issue "Define and throw a dedicated exception instead of using a generic one"

try {
    String stringPayload = jsonMapper.writeValueAsString(payload);
    log.info("Feedzai request: {}"<some object>);
    input.setPayload(new StringEntity(stringPayload, APPLICATION_JSON));
} catch (JsonProcessingException e) {
    throw new RuntimeException(e.getMessage());
}

I tried to replace catch "RuntimeException" from:

throw new RuntimeException(e.getMessage()); 

to throw new

RuntimeException(String.format("RuntimeException during processing JSON %s", e.getMessage()),e);

But getting same error. Could you please some one help me.

CodePudding user response:

Definition of RuntimeExteption:

RuntimeException and its subclasses are unchecked exceptions. Unchecked exceptions do not need to be declared in a method or constructor's throws clause if they can be thrown by the execution of the method or constructor and propagate outside the method or constructor boundary.

You have two options:

  1. Create a custom exception class
  2. Throw already caught JsonProcessingException

Code for the first option will be:

} catch (JsonProcessingException e) {
    //log message somewhere
    throw new MyCustomException(e.getMessage());
}

Code for the second option will be:

} catch (JsonProcessingException e) {
    //log message somewhere
    throw;
}
  • Related