javaintellij-ideanullpointerexceptionsonarlint

Sonarlint warns me against a possible NullPointerException, but in my mind, I did what was necessary to prevent it?


I've wrote this code that is working properly, but Sonarlint warns me against a wsr.getBody().getWorkspace() that could lead to a NullPointerException on wsr.getBody(), who could yield null, it says.

public WorkspaceSummary getWorkspace(String workspaceName) {
   try {
      ResponseEntity<GetWorkspaceResponse> wsr = this.workspacesApi.getWorkspaceWithHttpInfo(workspaceName, this.quiet);

      if (wsr == null || wsr.getBody() == null) {
         throw new RuntimeException("getWorkspaceWithHttpInfo a renvoyé une réponse nulle");
      }

      return wsr.getBody().getWorkspace();
   }
   catch(HttpClientErrorException e) {
      [...]
   }
}

enter image description here

But I believe not. In my mind, I did what was necessary to prevent it.

Sometimes obvious things that are in front of us we don't see them, this is why I am asking you if I missed something.


Solution

  • You assume that war.getBody() is consistent and always returns the same value. Sonar looks at the code and sees that you are recalculating or refetching the value, so basically you didn’t validate the new value, so the value can be null. If you save the value than there is no threat that the value will change.