Home > database >  Sonarqube shows NullPointerException bug even after null check is present in Java
Sonarqube shows NullPointerException bug even after null check is present in Java

Time:06-02

Sonarqube says there are 2 major bugs in this code, on the 2nd statement in if condition.

first:

A "NullPointerException" could be thrown; "getResponseHeaders()" can return null.

Second:

Result of "getResponseHeaders()" is dereferenced

private ResponseEntity<ErrorResponse> handleHttpStatusCodeException(HttpStatusCodeException exception) {
    ResponseEntity.BodyBuilder response = ResponseEntity.status(exception.getStatusCode());
    if (exception.getResponseHeaders() != null && exception.getResponseHeaders().getContentType() != null) {
        response.contentType(exception.getResponseHeaders().getContentType());
    }
    return response.body(createErrorResponse(exception.getResponseBodyAsString()));
}

Is there a way, I can change the code to avoid the bug ?

CodePudding user response:

Theoretically, another thread might change the result of exception.getResponseHeaders() after you checked it's non null but before you call it a second time. This kind of check-then-act is not always safe.

The safer way to handle this is to assign to a local

var headers = exception.getResponseHeaders();
if (headers != null) {
    var contentType = headers.getContentType();
    if (contentType != null) {
        response.contentType(contentType);
    } 
}

I think this is a little more readable than your solution anyway.

Of course, if your object isn't mutated by multiple threads or is immutable, then this warning is a false positive which could be ignored.

  • Related