Java 在try/catch上不应取消对空指针的引用
目前,我正在与SonarQu合作解决问题,但在如何处理不应取消引用的空指针方面,我遇到了麻烦。此问题由sonarqube显示 我的主要问题是,我正在使用try catch执行restemplate.exchange,并在try子句之前声明一个值为null的变量,然后在try中使用它。最后,我的方法返回一个值为restTemplate的响应Java 在try/catch上不应取消对空指针的引用,java,sonarqube,Java,Sonarqube,目前,我正在与SonarQu合作解决问题,但在如何处理不应取消引用的空指针方面,我遇到了麻烦。此问题由sonarqube显示 我的主要问题是,我正在使用try catch执行restemplate.exchange,并在try子句之前声明一个值为null的变量,然后在try中使用它。最后,我的方法返回一个值为restTemplate的响应 public MyDto exchangeUrlRequest(String url){ ResponseEntity<MyDto> respo
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();
}
public MyDto-exchangeUrlRequest(字符串url){
ResponseEntity responseDto=null;
试一试{
responseDto=restemplate.exchange(url,HttpMethod.PUT。。。
}捕获(HttpClientErrorE异常){
//这里有一些代码
}
返回responseDto.getBody();
}
这里的预期结果是解决sonarqube的问题。如何在没有“null”的情况下初始化“responseDto”,因为这是sonar的问题
我已经尝试在try子句中输入“ResponseEntity responseDto”来分配和返回相应的值,但必须在try/catch中返回一些内容。输入“new ResponseEntity”是错误的,因为我不知道http状态的答案是什么。您的代码需要对捕获某个异常时可能出现的
NullPointerException
做一些处理,因为在这种情况下,响应到
将为null
有很多方法可以解决这个问题。我推荐的解决方案不是在Java上使用null
返回或变量,请尝试使用它。您可以使用Optional
因此,该代码应该解决声纳问题:
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());
}
即使我不建议这样做,您也可以只检查nullresponseDto
,而不使用可选项
:
public Optional<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();
}
public可选交换eurlrequest(字符串url){
ResponseEntity responseDto=null;
试一试{
responseDto=restemplate.exchange(url,HttpMethod.PUT…);
}捕获(HttpClientErrorE异常){
//这里有一些代码
}
if(responseDto==null){
返回null;
}
返回responseDto.getBody();
}
public Optional<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();
}