We have a BaseException extends Exception
in our project, and basically all our other exceptions derive from this class. I want to change some methods that deal with the "cause stack" at runtime.
As starting point, I wrote the following method:
class BaseException extends Exception {
...
/**
* Helper: creates a list containing the complete "cause stack" of this exception.
* Please note: the exception on which this method is called is part of result!
*
* @return a {@link List} of all "causes" of this exception
*/
List<Throwable> getAllCauses() {
Throwable cause = this;
List<Throwable> causes = new ArrayList<>();
while (cause != null) {
causes.add(cause);
cause = cause.getCause();
}
return causes;
}
This gets the job done, although it is not perfect (name isn't exactly great, and single layer of abstraction is violated, too) .
But still: is there a "more elegant" way of collecting this result? Especially given the fact that it would helpful to directly return a Stream<Throwable>
.
( I am mainly wondering if there is a java8 lambda/idiom that could help here )