Exceptions thrown from before templates should not be added to Preconditions
timtebeek opened this issue · comments
What problem are you trying to solve?
When a before template throws a specific exception, that now makes it's way into the preconditions, as seen in openrewrite/rewrite-migrate-java@4bfadd2.
That means the templates will fail to match, since the exception is unlikely to be used in the matched template.
Describe the solution you'd like
Do not add exceptions to preconditions.
Have you considered any alternatives or workarounds?
- Enforce
throws Exception
from lambdas, rather than specific ones; not ideal, as it loses specificity on the user's side.
Additional context
Had some discussions with @knutwannheden around this; excluding the declared thrown exceptions from the lambda seems right, although we might want to double check if that is even an issue still.
We should be able to collect the imports using something like this:
Set<Symbol> allImports = new HashSet<>(ImportDetector.imports(template.getBody()));
allImports.addAll(ImportDetector.imports(template.getReturnType()));
template.getParameters().forEach(p -> allImports.addAll(ImportDetector.imports(p)));
template.getTypeParameters().forEach(p -> allImports.addAll(ImportDetector.imports(p)));
Excluding the method's throws
clause is important as it will otherwise add wrong UsesType
preconditions. One example would be when the template's throws
clause lists runtime exceptions. The code being matched might not have any corresponding catch
or throws
, so there should not be any corresponding UsesType
.