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

标签 java sonarqube

目前我正在使用 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/

相关文章:

java - 用冒号分隔小数点

java - 从 HashMap 中获取前 k 个值

msbuild - 代码覆盖率结果的 MSBuild.SonarQube.Runner.exe 结束命令出错

MSBuild SonarQube runner : "Failed to locate the code coverage command line tool" still with version 1. 0.1

sonarqube - Sonar Runner 默认日志记录级别

java - Maven依赖插件下线未下载某些插件

Java内存泄漏,只有Jenkins运行,Jenkins .war分析显示没有什么奇怪的

java - 将压缩的 Base64 字符串转换为其原始文件

java - log4j错误日志中面临的问题和异常处理

python - EXPRESSION_STMT 在 Python 语法中如何工作?