尝试修复 SonarQube 错误 - 可能会抛出 "NullPointerException"

try to fix SonarQube bug - A "NullPointerException" could be thrown

我遇到了一个奇怪的 Sonar 问题 - 可能会抛出“NullPointerException”。

下面是我的服务实现class。 emailNotificationServiceClient 是 FeignClient 接口,工作正常。

      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;

}

我知道我必须为对象添加 null 检查,然后我应该使用该对象。我已经试过了,但是不行。

我也试过 Java 8 Optional.ofNullable 但仍然面临同样的问题。

这是误报。 SonarCube 的规则有点“笨”。但你应该能够帮助它......像这样:

GenericRes<?> body = response.getBody();
if (body != null) {
    String message = body.getMessage();
    if (message != null && !message.isEmpty()) {
        return CompletableFuture.completedFuture(message);
    }
}

在我看来,这比 SonarCube 遇到问题的版本更具可读性。所以,这是一个“双赢”的解决方案。