Sonar complaining about logging and rethrowing the exception

前端 未结 4 1051
闹比i
闹比i 2020-12-06 04:32

I have the following piece of code in my program and I am running SonarQube 5 for code quality check on it after integrating it with Maven.

However, Sonar is complai

相关标签:
4条回答
  • 2020-12-06 05:16

    What sonar is asking you to do, is to persist the entire exception object. You can use something like:

        try {
            ...         
        } catch (Exception e) {
            logger.error("Error", e);
        }
    
    0 讨论(0)
  • 2020-12-06 05:18

    You should do it this way :

    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 shouldn't bother you anymore

    0 讨论(0)
  • 2020-12-06 05:20

    I stumbled across the same issue. I'm not 100% sure if I'm completely right at this point, but basically you should rethrow or log the complete Exception. Whereas e.getMessage() just gives you the detailed message but not the snapshot of the execution stack.

    From the 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.

    This means the solution provided by abarre works, because the whole exception object (sqle) is being passed to the logger.

    Hope it helps. Cheers.

    0 讨论(0)
  • 2020-12-06 05:21

    If you believe that SQLException can be safely ignored, then you can add it to the list of exceptions for squid:S1166 rule.

    1. Go to Rule-> Search squid:S1166.
    2. Edit exceptions in Quality Profile.
    3. Add SQLException to the list.
    0 讨论(0)
提交回复
热议问题