초이로그

[SonarLint] 예외는 로그로 남기던가 다시 던져야한다. 그러나 둘 다 하면 안된다(java:S2139) 본문

Stacks

[SonarLint] 예외는 로그로 남기던가 다시 던져야한다. 그러나 둘 다 하면 안된다(java:S2139)

수연초이 2022. 10. 14. 10:50
Exceptions should be either logged or rethrown but not both

In applications where the accepted practice is to log an Exception and then rethrow it, you end up with miles-long logs that contain multiple instances of the same exception. In multi-threaded applications debugging this type of log can be particularly hellish because messages from other threads will be interwoven with the repetitions of the logged-and-thrown Exception. Instead, exceptions should be either logged or rethrown, not both.

Code Smell: 🚫 Major

 

애플리케이션의 try-catch문에서 예외를 로그로도 기록하고 다시 던지면, 똑같은 예외의 인스턴스를 갖는 매우 긴 로그가 생성된다. 멀티 스레드 애플리케이션 환경에서는 다른 스레드의 로그와 예외가 섞여서 디버깅하기가 매우 힘들어진다. 그러니 예외는 로그로만 남기거나 또다른 예외로 던지기 둘 중하나만 하자.

 

잘못된 코드 예시

catch (SQLException e) {
  ...
  LOGGER.log(Level.ERROR,  contextInfo, e);
  throw new MySQLException(contextInfo, e);
}

 

좋은 코드 예시

catch (SQLException e) {
  ...
  throw new MySQLException(contextInfo, e);
}
catch (SQLException e) {
  ...
  LOGGER.log(Level.ERROR,  contextInfo, e);
  // handle exception...
}

출처

https://rules.sonarsource.com/java/RSPEC-2139