I’ve encountered an issue with SonarSource’s Rule S2139 (Exceptions should be either logged or rethrown but not both).
According to the S2139 rule description:
When an exception is logged and rethrown, the upstream code may not be aware that the exception has already been logged. As a result, the same exception gets logged multiple times, making it difficult to identify the root cause of the issue. This can be particularly problematic in multi-threaded applications where messages from other threads can be interwoven with the repeated log entries.
However, in my case, the code smell is detected in Program.cs
, which is the most upstream code. In the code, I’m catching exceptions and logging the error message as follows:
try
{
// omitting code
}
catch (Exception exception)
{
logger.LogError(exception, "Stopped program because of exception");
throw;
}
finally
{
logger.LogInformation("**** SHUTDOWN Program ****");
LogManager.Shutdown();
}
Am I misunderstanding the rule, or could this be a false positive? I’m aware of the “False Positive” and “Won’t Fix” options in SonarQube or suppressing the warning, but I would like to confirm my understanding before proceeding.
Any insights would be appreciated. Thanks in advance!