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

问题描述 投票:0回答:2

我面临一个奇怪的声纳问题 - 可能会抛出“NullPointerException”。

下面是我的服务实现类。 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 类 -

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class GenericRes<T> {

    private String message;
    
    private T data;

}

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

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

java spring-boot rest nullpointerexception sonarqube
2个回答
7
投票

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

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

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


0
投票
https://community.sonarsource.com/t/java-s2259-a-nullpointerexception-could-be- thrown-getmessage-can-return-null/78815

© www.soinside.com 2019 - 2024. All rights reserved.