目前我正在使用 SonarQube 解决问题,但我遇到了如何处理不应取消引用的空指针的问题。此问题由 SonarQube 显示。
我的主要问题是因为我正在使用 try-catch 执行 restTemplate.exchange 并在子句 try 之前声明一个具有空值的变量,然后在 try 中使用它。最后,我的方法返回值为 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();
}
这里的预期结果是解决sonarqube的问题。如何处理没有“null”的“responseDto”的初始化,因为将问题抛给了 Sonar 。
我已经试过把ResponseEntity<MyDto> responseDto
在我的 try 子句中,分配并返回相应的值,但它必须从 try/catch 中返回一些东西。放一个new ResponseEntity
是错误的,因为我不知道 http 状态的答案是什么。
最佳答案
您的代码需要对可能的 NullPointerException
做些什么当捕获到某些异常时,因为在这种情况下 responseDto
将为空。
有很多方法可以解决这个问题。我推荐的解决方案不适用于 null
Java 上的返回值或变量,尝试 avoid它。您可以使用 Optional
相反。
因此,这段代码应该可以解决 Sonar 问题:
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());
}
您还可以消除 null
使用 Optional<ResponseEntity<MyDto>>
检查,比如:
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();
}
即使我不推荐这个,你也可以检查 null responseDto
不使用 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();
}
关于java - 不应在 try/catch 上取消引用 SonarQube 空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56782799/