SonarQube空指针不应在try / catch上取消引用

时间:2019-06-27 01:32:30

标签: java sonarqube

当前,我正在与SonarQube合作解决问题,但是在处理不应取消引用的空指针方面遇到了麻烦。此问题由sonarqube显示。

我的主要问题是因为我正在使用try-catch进行restTemplate.exchange,并在try子句之前声明一个具有null值的变量,然后在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();
}

此处的预期结果是使用声纳法解决问题。如何在没有“ null”的情况下初始化“ responseDto”,因为这将问题扔到了声纳上。

我已经尝试将“ ResponseEntity responseDto”放入我的try子句中,以分配和返回各自的值,但是必须将其从try / catch中返回。放置“新ResponseEntity”是错误的,因为我不知道HTTP状态的答案是什么。

1 个答案:

答案 0 :(得分:0)

当捕获到某些异常时,您的代码需要对可能的NullPointerException做一些事情,因为在这种情况下responseDto将为空。

有很多方法可以解决此问题。我推荐的解决方案不适用于Java上的null返回值或变量,请尝试avoid。您可以改用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());
}

您还可以使用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();
}

即使我不推荐这样做,也可以不使用responseDto就检查空Optional

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();
}