Sonar抱怨记录并重新抛出exception
我在我的程序中有以下代码,我在运行SonarQube 5后,将它与Maven集成后进行代码质量检查。
然而,Sonar抱怨我应该记录或重新抛出此exception 。
我在这里想念的是什么? 我还没有记录exception吗?
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); }
声纳不应该打扰你了
声纳要求你做的是坚持整个exception对象。 您可以使用以下内容:
try { ... } catch (Exception e) { logger.error("Error", e); }
如果您认为可以安全地忽略SQLException,那么您可以将其添加到squid例外列表中:S1166规则。
- 转到Rule-> Search squid:S1166。
- 编辑质量配置文件中的例外
- 将SQLException添加到列表中。
我偶然发现了同样的问题。 我不是百分百确定我是否完全正确,但基本上你应该重新抛出或记录完整的exception。 而e.getMessage()
只是为您提供详细消息,而不是执行堆栈的快照。
来自Oracle文档(Throwable) :
throwable包含其创建时线程执行堆栈的快照。 它还可以包含一个消息字符串,该字符串提供有关错误的更多信息。 随着时间的推移,throwable可以抑制其他throwable的传播。 最后,throwable还可以包含一个原因:另一个throwable导致构造这个throwable。 这种因果信息的记录被称为链式exception工具,因为原因本身可能有原因,等等,导致exception的“链”,每个exception由另一个引起。
这意味着abarre提供的解决方案有效,因为整个exception对象(sqle)正在传递给记录器。
希望能帮助到你。 干杯。