Common utility for finding exceptions

I wrote this little helper method to find the chain of exceptions for a specific exception (either equal or superclass). However, this seems like a solution to a common problem, so he thought it already exists somewhere, perhaps in a library that I already imported. So, any ideas on if / where this could exist?

boolean exceptionSearch(Exception base, Class<?> search) {

    Throwable e = base;

    do {
        if (search.isAssignableFrom(e.getClass())) {
            return true;
        }
    } while ((e = e.getCause()) != null);

    return false;
}
+3
source share
3 answers

Take a look at the Google Guava project. They have quite a few handy classes, including one for exceptions. For example, the functionality you just requested can be implemented as follows:

    boolean exceptionSearch(Exception base, Class<?> search) {
        return Throwables.getCausalChain(base).contains(search);
    }

Source code for this class: Throwables

Enjoy it!

+2
source

, - , . , . , .

0

, Apache commons-lang ExceptionUtils.indexOfType :

public static int indexOfType (java.lang.Throwable throwable, java.lang.Class type)

0
source

Source: https://habr.com/ru/post/1785582/


All Articles