-
Notifications
You must be signed in to change notification settings - Fork 21
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add recipe to clone an exception argument #141
Comments
Thanks for the suggestion! Replicated with this unit test @Test
void showStacktraceInsteadOfExceptionToString() {
//language=java
rewriteRun(
java(
"""
import org.slf4j.Logger;
class A {
void method(Logger log) {
try {
throw new RuntimeException("");
} catch (Exception e) {
log.error("An error occurred: {}", e);
}
}
}
""",
"""
import org.slf4j.Logger;
class A {
void method(Logger log) {
try {
throw new RuntimeException("");
} catch (Exception e) {
log.error("An error occurred: {}", e.getMessage(), e);
}
}
}
"""
)
);
} That now exits the recipe early, because the last parameter is already an exception. Lines 98 to 102 in 53f8787
Instead we should probably count the number of placeholders in the logging statement early, and from there decide if we should insert a new second to last argument. Lines 161 to 169 in 53f8787
|
Yes, something like this. There is already a test with Lines 96 to 118 in f5c66f7
It would be nice to have the same refactoring with Note: the number of placeholders is slightly more complicated to compute due to simple escaping rules:
|
Agree with you there that the current handling is perhaps too simple; and yes would be nice to have this handling here. I'll be traveling for the next five weeks, but can try to provide guidance if needed on this one. |
What problem are you trying to solve?
When logging exceptions using SLF4J or Log4j API, a common mistake is to add a placeholder for the exception in the message format:
Describe the solution you'd like
Currently there is a CompleteExceptionLogging rewrite rule that deals with the case:
This rule could be expanded to rewrite the first example into either:
or
Have you considered any alternatives or workarounds?
Palantir already offers a LoggerInterpolationConsumesThrowable Error Prone rule, that could be expanded to generate a code change suggestion.
Are you interested in contributing this feature to OpenRewrite?
Right now I don't have time for the OpenRewrite rules already assigned to me. If this is not solved till September, I can provide a PR.
The text was updated successfully, but these errors were encountered: