声纳抱怨记录并重新抛出异常

Sonar complaining about logging and rethrowing the exception

我的程序中有以下代码,我 运行 SonarQube 5 在与 Maven 集成后对其进行代码质量检查。

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

我在这里错过了什么?我不是已经在记录异常了吗?

 private boolean authenticate(User user) {
        boolean validUser = false;
        int validUserCount = 0;
        try {
            DataSource dataSource = (DataSource) getServletContext().getAttribute("dataSource");
            validUserCount = new MasterDao(dataSource).getValidUserCount(user);
        } catch (SQLException sqle) {
            LOG.error("Exception while validating user credentials for user with username: " + user.getUsername() + " and pwd:" + user.getPwd());
            LOG.error(sqle.getMessage());
        }
        if (validUserCount == 1) {
            validUser = true;
        }
        return validUser;
    }

你应该这样做:

try {
    DataSource dataSource = (DataSource) getServletContext().getAttribute("dataSource");
    validUserCount = new MasterDao(dataSource).getValidUserCount(user);
} catch (SQLException sqle) {
    LOG.error("Exception while validating user credentials for user with username: " +
            user.getUsername() + " and pwd:" + user.getPwd(), sqle);
}

Sonar 不应该再打扰你了

如果您认为可以安全地忽略 SQLException,则可以将其添加到 squid:S1166 规则的例外列表中。

  1. 转到规则-> 搜索 squid:S1166。
  2. 编辑质量配置文件中的例外情况。
  3. 将 SQLException 添加到列表中。

我偶然发现了同样的问题。我不是 100% 确定我在这一点上是否完全正确,但基本上你应该重新抛出或记录完整的异常。而 e.getMessage() 只是给你详细的消息,而不是执行堆栈的快照。

来自Oracle docs (Throwable)

A throwable contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. Over time, a throwable can suppress other throwables from being propagated. Finally, the throwable can also contain a cause: another throwable that caused this throwable to be constructed. The recording of this causal information is referred to as the chained exception facility, as the cause can, itself, have a cause, and so on, leading to a "chain" of exceptions, each caused by another.

这意味着 abarre 提供的解决方案有效,因为整个异常对象 (sqle) 都被传递给了记录器。

希望对您有所帮助。 干杯。

sonar 要求您做的是持久化整个异常对象。 您可以使用类似的东西:

    try {
        ...         
    } catch (Exception e) {
        logger.error("Error", e);
    }