这是关于either ... or,参见声纳规则规范 RSPEC-2139 https://rules.sonarsource.com/java/tag/error-handling/RSPEC-2139:
异常应该被记录或重新抛出但不是两者都
为了遵守规则,请决定:
- 仅记录:
try {
object = MAPPER.readValue(jsonString.toString(), valueType);
} catch (IOException io) {
log.error(ERROR_LOG_STR + " in method getObjectFromJson(). Exception Message={}, Exception Stack ={}",
io.getMessage(), io);
}
- 或仅抛出:
try {
object = MAPPER.readValue(jsonString.toString(), valueType);
} catch (IOException io) {
throw new ServiceException(ErrorMessages.JSON_SERIALIZATION_ERROR, io); // would use the full exception, not only the wrapped .getCause()
}
奖励:如何实现两者并简化
您还可以另外登录全局或本地错误处理拦截器,例如 Spring 的@ControllerAdvice
带注释的错误处理程序。
大多数记录器允许传递Throwable
当以错误级别记录时。
例如使用Slf4j https://www.slf4j.org/apidocs/org/slf4j/Logger.html#error(java.lang.String,java.lang.Throwable): log.error(ERROR_LOG_STR + " in method getObjectFromJson(): " + io.getMessage(), io)
也可以看看:
- 如何使用 SLF4J 记录带有占位符的异常和消息 https://stackoverflow.com/questions/5951209/how-to-log-exception-and-message-with-placeholders-with-slf4j
- 拜尔东教程:使用 SLF4J 记录异常 https://www.baeldung.com/slf4j-log-exceptions
相关规则
RSPEC-1166 https://rules.sonarsource.com/java/tag/error-handling/RSPEC-1166:异常处理程序应该保留原始异常
The 规格特征 https://jira.sonarsource.com/browse/RSPEC-1166已于 2018-11-02 版本 5.9 解决,Java 的实现 https://jira.sonarsource.com/browse/SONARJAVA-30292019-02-15 已修复,版本 5.11。
⚠️ 仅部分修复:
The 标记重复 https://stackoverflow.com/questions/70608131/either-log-this-exception-and-handle-it-or-rethrow-it-with-some-contextual-info/70608728#comment124817603_70608131
and 奥布根的回答 https://stackoverflow.com/a/70608346/5730279不要完全解决这里的两重情况:
- 他们修复了 RSPEC-1166
- 但不是 RSPEC-2139
应对 RSPEC-1166 的类似问题:
-
SONAR 抱怨记录和重新抛出异常 https://stackoverflow.com/questions/39411450/sonar-complaining-about-logging-and-rethrowing-an-exception, 2016 年询问
-
记录或重新抛出此异常 https://stackoverflow.com/questions/32197329/either-log-or-rethrow-this-exception,2015 年询问
-
声纳抱怨记录并重新抛出异常 https://stackoverflow.com/questions/28122271/sonar-complaining-about-logging-and-rethrowing-the-exception,2015 年询问