public class EitherLogOrThrowCheck
extends com.puppycrawl.tools.checkstyle.api.AbstractCheck
Either log the exception, or throw it, but never do both. Logging and throwing results in multiple log messages for a single problem in the code, and makes problems for the support engineer who is trying to dig through the logs. This is one of the most annoying error-handling antipatterns. All of these examples are equally wrong.
Examples:
catch (NoSuchMethodException e) {
LOG.error("Message", e);
throw e;
}
or
catch (NoSuchMethodException e) {
LOG.error("Message", e);
throw new MyServiceException("AnotherMessage", e);
}
or
catch (NoSuchMethodException e) {
e.printStackTrace();
throw new MyServiceException("Message", e);
}
What check can detect:
Loggers
catch blockcatch parameter exception or its messagecatch parameter exceptioncatch parameter
exceptioncatch parameter exception
What check can not detect:
getLogger().error("message", e)
MyAnotherClass.LOGGER.error("message", e);
Default parameters are:
Note that check works with only one logger type. If you have multiple different loggers, then create another instance of this check.
| Modifier and Type | Field and Description |
|---|---|
static String |
MSG_KEY
Key for error message.
|
| Constructor and Description |
|---|
EitherLogOrThrowCheck() |
| Modifier and Type | Method and Description |
|---|---|
int[] |
getAcceptableTokens() |
int[] |
getDefaultTokens() |
int[] |
getRequiredTokens() |
void |
setLoggerFullyQualifiedClassName(String loggerFullyQualifiedClassName)
Set logger full class name and logger simple class name.
|
void |
setLoggingMethodNames(String... loggingMethodNames)
Set logging method names.
|
void |
visitToken(com.puppycrawl.tools.checkstyle.api.DetailAST ast) |
beginTree, clearMessages, destroy, finishTree, getFileContents, getLine, getLines, getMessages, getTabWidth, getTokenNames, init, isCommentNodesRequired, leaveToken, log, log, log, setFileContents, setTabWidth, setTokensfinishLocalSetup, getCustomMessages, getId, getMessageBundle, getSeverity, getSeverityLevel, setId, setSeveritypublic static final String MSG_KEY
public void setLoggerFullyQualifiedClassName(String loggerFullyQualifiedClassName)
loggerFullyQualifiedClassName - Logger full class name. Example: org.slf4j.Logger.public void setLoggingMethodNames(String... loggingMethodNames)
loggingMethodNames - Logger method names.public int[] getDefaultTokens()
getDefaultTokens in class com.puppycrawl.tools.checkstyle.api.AbstractCheckpublic int[] getAcceptableTokens()
getAcceptableTokens in class com.puppycrawl.tools.checkstyle.api.AbstractCheckpublic int[] getRequiredTokens()
getRequiredTokens in class com.puppycrawl.tools.checkstyle.api.AbstractCheckpublic void visitToken(com.puppycrawl.tools.checkstyle.api.DetailAST ast)
visitToken in class com.puppycrawl.tools.checkstyle.api.AbstractCheckCopyright © 2021. All rights reserved.