简体   繁体   中英

Is critical SonarLint issue S1166 in my Java code a false positive or not?

SonarLint 1.0.0 for Eclipse flags a critical issue in my code and I can't see why and how to fix it. It really looks like a false positive to me—or am I missing something?

import org.apache.log4j.Logger;

[...]

public final class Foo {

    private static final Logger logger = Logger.getLogger(Foo.class);

    [...]

    public static void foo() {

        MyCommand command = new MyCommand(foo, bar);
        try {
            commandService.executeCommand(command);
        } catch (CommandException e) {
            logger.error("My command execution failed", e);
        }
    }

    [...]

Here's an excerpt of the matching SonarLint rule description :

When handling a caught exception, the original exception's message and stack trace should be logged or passed forward.

Noncompliant Code Example

\n// Noncompliant - exception is lost \ntry { /* ... */ } catch (Exception e) { LOGGER.info("context");  }    \n\n// Noncompliant - exception is lost (only message is preserved)        \ntry { /* ... */ } catch (Exception e) { LOGGER.info(e.getMessage());  } \n\n// Noncompliant - exception is lost \ntry { /* ... */ } catch (Exception e) { throw new RuntimeException("context");  } \n

Compliant Solution

\ntry { /* ... */ } catch (Exception e) { LOGGER.info(e);  }    \n\ntry { /* ... */ } catch (Exception e) { throw new RuntimeException(e);  } \n\ntry { /* ... */ } catch (RuntimeException e) { \n    doSomething();   \n    throw e; \n} catch (Exception e) { \n    // Conversion into unchecked exception is also allowed \n    throw new RuntimeException(e); \n} \n

In my opinion, my code qualifies for the first variant of the given compliant solutions, but SonarLint does not accept it.

There was another discussion of Sonar rule S1166 a little while ago, but it's not really about the same issue I have.

Edit: In response to question below: I use log4j for logging. I expanded the code to reflect this.

You are, in fact, logging the original exception's message and stack trace; this is an erroneous finding.

It may be that the rule doesn't have specific knowledge of Log4j, but lacking omniscience of all logging libraries, the fact that the exception is passed as a parameter could suffice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM