I am facing one strange Sonar issue - A "NullPointerException" could be thrown.
Below is my service implementation class. emailNotificationServiceClient is FeignClient Interface which works fine.
try {
// send POST request
ResponseEntity<GenericRes<?>> response = emailNotificationServiceClient.sendEmail(payload);
// check response
if (response != null) {
if (response.getStatusCode() == HttpStatus.OK)
log.info("Email Send Successful : {}", response.getBody());
else
log.info("Email Send Failed : {}", response.getBody());
if (response.getBody() != null && response.getBody().getMessage() != null && !response.getBody().getMessage().isEmpty())
return CompletableFuture.completedFuture(response.getBody().getMessage());
}
} catch (Exception e) {
log.error("Error while sending email - sendEmailNotification in esb", e);
return CompletableFuture.completedFuture(e.getMessage());
}
GenericRes class -
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class GenericRes<T> {
private String message;
private T data;
}
I know that I have to add null check for object and then I should use that object. I have tried that but it won't work.
I have also tried Java 8 Optional.ofNullable but still facing same problem.
It is a false positive. SonarCube's rule is a bit "dumb". But you should be able to help it out ... something like this:
GenericRes<?> body = response.getBody();
if (body != null) {
String message = body.getMessage();
if (message != null && !message.isEmpty()) {
return CompletableFuture.completedFuture(message);
}
}
To my mind, that is more readable than the versions that SonarCube is having trouble with. So, that is a "win - win" solution.