'In Groovy(/Java) how would I remove the current function from the stackTrace when throwing an Exception?
I'd like to provide a function for throwing exceptions rather than throwing them directly. E.g. instead of writing:
def foo() {
def result = command_result("foo");
if (!result) {
throw new Exception("Bla!");
}
return result;
}
I'd like to write this:
def foo() {
return command_result("foo") ?: error("Bla!");
}
which requires a function error() to be defined:
def error(msg) {
throw new Exception(msg);
}
But of course I now have error() on top of the call stack, so if I wrote
try {
print(foo());
} catch(Exception error) {
print("ERROR: ${error.stackTrace.head()}: ${error}");
}
I'd get something like
ERROR: Script1.error(Script1.groovy:19): java.lang.Exception: Bla!
To get rid of error:19 on the stack I could just extract the second item on error.stackTrace I guess but that would force me to have one generic try/catch block.
Is it possible to provide such a functionality in Groovy (I guess it would be the same in Java) i.e. (re) throwing an Exception with the current function removed from the back trace?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
