简体   繁体   中英

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

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM