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

h4cxqtbf  于 2024-01-06  发布在  Spring
关注(0)|答案(2)|浏览(234)

我面临一个奇怪的声纳问题-一个“NullPointerException”可能会抛出。
下面是我的服务实现类。emailNotificationServiceClient是FeignClient接口,工作正常。

  1. try {
  2. // send POST request
  3. ResponseEntity<GenericRes<?>> response = emailNotificationServiceClient.sendEmail(payload);
  4. // check response
  5. if (response != null) {
  6. if (response.getStatusCode() == HttpStatus.OK)
  7. log.info("Email Send Successful : {}", response.getBody());
  8. else
  9. log.info("Email Send Failed : {}", response.getBody());
  10. if (response.getBody() != null && response.getBody().getMessage() != null && !response.getBody().getMessage().isEmpty())
  11. return CompletableFuture.completedFuture(response.getBody().getMessage());
  12. }
  13. } catch (Exception e) {
  14. log.error("Error while sending email - sendEmailNotification in esb", e);
  15. return CompletableFuture.completedFuture(e.getMessage());
  16. }

字符串
GenericRes类-

  1. @Data
  2. @Builder
  3. @AllArgsConstructor
  4. @NoArgsConstructor
  5. public class GenericRes<T> {
  6. private String message;
  7. private T data;
  8. }


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


polhcujo

polhcujo1#

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

  1. GenericRes<?> body = response.getBody();
  2. if (body != null) {
  3. String message = body.getMessage();
  4. if (message != null && !message.isEmpty()) {
  5. return CompletableFuture.completedFuture(message);
  6. }
  7. }

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

相关问题