【问题标题】:Sonar complaining logging or rethrowing the exception声纳抱怨记录或重新抛出异常
【发布时间】:2022-01-12 13:00:58
【问题描述】:

当我在与 Maven 集成后运行 SonarQube 进行代码质量检查时,我有以下代码。

但是,Sonar 抱怨我应该记录或重新抛出此异常。

我在这里缺少什么?谁能帮帮我。

代码

public ShippingResponse processShipping(ShippingRequest request) {
        log.debug("Processing Reservation Request ....");
        try{
            return helper.processShippingMethod(request);
        } catch (ServiceException serviceException) {
            log.error(RESERVATION_EXCE, ExceptionUtils.getStackTrace(serviceException));
            throw serviceException;
        } catch (Exception e) {
            throw new ServiceException(ErrorMessages.EPO_SM_ERR_03, e.getMessage());
        }
    }

【问题讨论】:

  • 与上述解决方案相比,没有我的 catch 块差异
  • 如果您阅读答案,您会发现这是完全相同的问题,因为您没有使用异常对象。您只是传递异常消息,导致您丢失所有堆栈跟踪信息
  • LOG.error("Exception", e);
  • 这条线是不是必须要添加到我的catch块中?

标签: spring-boot maven sonarqube


【解决方案1】:

Sonar 试图说明的一点是,您理想地打印或保留异常的根本原因,因此基本上是堆栈。您通过传递异常对象来保留它,因为如果您只保留消息,您将丢失所有这些信息。为了让声纳满意,您要么打印堆栈跟踪 (log.error(ErrorMessages.EPO_SM_ERR_03, e)),要么重新抛出一个新异常,将 Throwable 对象传递给构造函数。

所以理想的解决方案是像这样使用 ServiceException;

public class ServiceException extends Exception {
    public ServiceException(String message, Throwable cause) {
        super(message, cause);
    }
}
throw new ServiceException(ErrorMessages.EPO_SM_ERR_03, e);

【讨论】:

    猜你喜欢
    • 2015-03-23
    • 2017-01-17
    • 2015-11-18
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 2012-02-21
    • 2020-02-15
    相关资源
    最近更新 更多