Reputation: 29
Currently I'm working with SonarQube solving issues but I'm facing a trouble to how handle null pointers that shouldn't be dereferenced. This issues is displayed by SonarQube.
My main problem is because I'm doing a restTemplate.exchange with try-catch and declaring a variable with null value before the clause try and then using it inside the try. Finally my method is returning a response with value of restTemplate.
public MyDto exchangeUrlRequest(String url){
ResponseEntity<MyDto> responseDto = null;
try{
responseDto = restTemplate.exchange(url, HttpMethod.PUT...
}catch(HttpClientErrorException e){
//some code here
}
return responseDto.getBody();
}
The expected result here is solve the issue with sonarqube. How handle the initialization of "responseDto" without "null" because is throwing the issue on sonar.
I already tried to put ResponseEntity<MyDto> responseDto
inside my try clause assigning and returning the respective value but its mandatory to return something out the try/catch. Put a new ResponseEntity
is wrong because I won't know what will be the answer for the status of http.
Upvotes: 3
Views: 7024
Reputation: 19050
Your code needs to do something about the possible NullPointerException
when some exception is caught, because in this scenario the responseDto
will be null.
There are many ways to resolve this. The solution that I recommend is not work with null
returns or variables on Java, try to avoid it. You can use Optional
instead.
So, this code should address the Sonar problem:
public Optional<MyDto> exchangeUrlRequest(String url){
ResponseEntity<MyDto> responseDto;
try{
responseDto = restTemplate.exchange(url, HttpMethod.PUT...);
} catch(HttpClientErrorException e) {
//some code here
}
if (responseDto == null) {
return Optional.empty();
}
return Optional.of(responseDto.getBody());
}
You can also eliminate the null
check using Optional<ResponseEntity<MyDto>>
, like:
public Optional<MyDto> exchangeUrlRequest(String url){
Optional<ResponseEntity<MyDto>> optResponseDto = Optional.empty();
try{
optResponseDto = Optional.of(restTemplate.exchange(url, HttpMethod.PUT...));
} catch(HttpClientErrorException e) {
//some code here
}
if (!optResponseDto.isPresent()) {
return Optional.empty();
}
return optResponseDto.get().getBody();
}
Even I don't recommend this, you can just check the null responseDto
without any use of Optional
:
public MyDto exchangeUrlRequest(String url){
ResponseEntity<MyDto> responseDto = null;
try{
responseDto = restTemplate.exchange(url, HttpMethod.PUT...);
} catch(HttpClientErrorException e) {
//some code here
}
if (responseDto == null) {
return null;
}
return responseDto.getBody();
}
Upvotes: 2