All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.plugins.csharp.S2139.html Maven / Gradle / Ivy

There is a newer version: 10.2.0.105762
Show newest version

Why is this an issue?

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.

Exceptions

This rule will not generate issues if, within the catch block, one of the following conditions are met:

  • The logs generated within the catch block do not contain any references to the exception being caught.
  • The exception being thrown from the catch block is not the same exception that is being caught.

How to fix it

To address this issue, it is recommended to modify the code to log exceptions only when they are handled locally. In all other cases, simply rethrow the exception and allow the higher-level layers of the application to handle the logging and appropriate actions.

Code examples

Noncompliant code example

try {}
catch (Exception ex)
{
  logger.LogError(ex.Message);
  throw;
}

Compliant solution

try {}
catch (Exception ex)
{
  logger.LogError(ex.Message);
  // Handle exception
}

or

try {}
catch (Exception ex)
{
  // ...
  throw;
}

Resources

Documentation

Articles & blog posts





© 2015 - 2024 Weber Informatics LLC | Privacy Policy