【问题标题】:SonarQube showing error when exception is there存在异常时 SonarQube 显示错误
【发布时间】:2019-10-24 13:07:47
【问题描述】:

对于下面的代码,Sonarqube 显示错误,说“要么记录或重新抛出此异常”。 fof catch 块,我们怎么处理呢

  private ResponseEntity<String> getResponse(String url,
                                                      String logName,
                                                      HttpMethod httpMethod,
                                                      HttpEntity<String> httpEntity,
                                                      HttpServletRequest httpServletRequest)
    {
        httpServletRequest.setAttribute("api", logName);
        ResponseEntity<String> checkEntity;
        try {
            if(logName.equals("Activate All Offer Api")){
                checkEntity = requestFactory.getRestTemplate().exchange(url, httpMethod, httpEntity, String.class);
            }else {
                checkEntity = restTemplate.exchange(url, httpMethod, httpEntity, String.class);
            }
        } catch (Exception e) {
        throw new LocalHttpClientErrorException(e.getLocalizedMessage());
    }
        return checkEntity;
    }

【问题讨论】:

  • 它告诉你正确地重新抛出异常,正确地并不意味着切断原始异常的堆栈跟踪,只使用本地化的异常消息。

标签: java sonarqube


【解决方案1】:

要使警告消失,您需要将原始异常作为原因附加到 LocalHttpClientErrorException 的构造函数参数中,或者如果这不可能,请使用 initCause(Throwable) 方法。但也存在一些其他问题。

  1. 您正在捕获一般异常。这始终是严重代码异味的标志。
  2. 您正在将本地化消息传递给 LocalHttpClientErrorException。本地化应该是 UI 层的职责,而不是业务逻辑。

【讨论】:

  • 我会将“总是一个标志”软化为“通常”、“经常”等。有时您确实需要捕获异常,例如你在 try 中调用了一个 Callable 的调用方法。
  • 是的,我想这很公平。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-20
  • 1970-01-01
  • 2012-01-27
  • 2018-07-03
  • 2011-11-03
  • 2019-06-28
相关资源
最近更新 更多