Search code examples
javasonarqube

Possible null pointer dereference in [...] due to return value of called method


Small question regarding a SonarQube flagged issue I do not understand please.

My snippet is very simple.

VaultTokenResponse  result = getWebClient().mutate().baseUrl(vaultUrl).build().post().retrieve().bodyToMono(VaultTokenResponse.class).block();
 
String              vaultToken     = result.getToken().getToken();

However, on the second line here, Sonarqube is telling me:

findbugs:NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE Style - Possible null pointer dereference due to return value of called method

The return value from a method is dereferenced without a null check, and the return value of that method is one that should generally be checked for null. This may lead to a NullPointerException when the code is executed

I am a bit unsure what this means.

Most of all, I do not know how to fix this.

Little help please?

Thank you


Solution

  • result.getToken() might return null. So when you call result.getToken().getToken() you are calling getToken() on a null reference. Thus a NullPointerException will be thrown.

    So you could do something like

    YourClass token = result.getToken();
    if(token != null) {
        String vaultToken = token.getToken(); // whatever you want to do with it
    }
    else {
        // error handling
    }