I’m trying to find a way to quietly wrap the main method of a class in a try/catch block.
What I’m imagining is a static version of invokeMethod, where I can simply intercept the main method call and wrap it in my superclass:
@Log4j2
class Wrapper {
static def invokeMethod(String name,args) {
if(name == 'main') {
def main = subclass.&main // Unsure how I would get the subclass.
try {
main(args)
} catch(any) {
log.error("An unhandled exception was thrown.",any)
}
} else {
def fun = subclass.&"$name"
fun(args)
}
}
}
class Main extends Wrapper {
static void main(args) {
throw new Exception("This should be logged.")
}
}
Upon execution, assuming I’ve configured Log4j2 properly, the Exception would be logged.
Is there a way to accomplish this without writing code directly to the subclass’s main method definition?
1