Spring Boot 尝试修复SonarQube错误-可能会引发“NullPointerException”

h4cxqtbf  于 5个月前  发布在  Spring
关注(0)|答案(2)|浏览(95)

我面临一个奇怪的声纳问题-一个“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;

}


我知道我必须为对象添加空检查,然后我应该使用该对象。我已经尝试过了,但它不会工作。
x1c 0d1x的数据
我也尝试过Java 8 Optional.ofNullable,但仍然面临同样的问题。


polhcujo

polhcujo1#

这是一个假阳性。SonarCube的规则有点“愚蠢”。但你应该能够帮助它.类似于这样的东西:

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

字符串
在我看来,这比SonarCube遇到麻烦的版本 * 可读性更强 *。所以,这是一个“双赢”的解决方案。

相关问题