I am trying to create a java rule for my java repositories.
My objective is to create this rule:
Any object derived from Exception should not be passed as argument in log.error method.
I have followed the https://github.com/SonarSource/sonar-java/blob/master/docs/CUSTOM_RULES_101 and created the rule as such:
@Rule(key = "AvoidLogErrorWithExceptionRule")
public class AvoidLogErrorWithExceptionCheck extends IssuableSubscriptionVisitor {
@Override
public List<Tree.Kind> nodesToVisit() {
return Collections.singletonList(Tree.Kind.METHOD_INVOCATION);
}
@Override
public void visitNode(Tree tree) {
MethodInvocationTree methodInvocation = (MethodInvocationTree) tree;
if (methodInvocation.methodSymbol().name().equals("error") &&
methodInvocation.methodSymbol().owner().name().equalsIgnoreCase("log")) {
// Check arguments for types or subtypes of Exception
for (ExpressionTree argument : methodInvocation.arguments()) {
Type argumentType = argument.symbolType();
if (argumentType.isSubtypeOf("java.lang.Exception")) {
reportIssue(argument, "Avoid passing Exception or subclasses to log.error directly.");
}
}
}
}
}
For log.error statements in testfile, I see that it shows unknownMethod and unknownTypeSymbol etc.
Example testfile:
@Slf4j
public class TrialClass {
int doSomething(int a) {
try{
//do something
} catch (Exception e){
log.error("Caught exception",e);
}
return 0;
}
}
Also I have gone through Java rule for redundant log actions, but all the repos usually implement annotation based loggers. Does that mean there is no way of implementing this rule?