Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save VenkataRaju/07b32a4911e8d06ae9e5 to your computer and use it in GitHub Desktop.
Save VenkataRaju/07b32a4911e8d06ae9e5 to your computer and use it in GitHub Desktop.
Check if any Throwable matches the Predicate in Throwable chain
package test;
import java.io.IOException;
import java.util.function.Predicate;
public class AnyThrowableMatchesPredicateInThrowableChain
{
public static void main(String[] args) throws IOException
{
Throwable throwable = new Throwable("sdsdf");
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable = new Throwable("Helldo", throwable);
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable = new Throwable("Helldo", throwable);
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable = new Throwable("Helldo", throwable);
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable = new Throwable("Helldo", throwable);
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable = new Throwable("Helldo", throwable);
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable = new Throwable("Hellsos", throwable);
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable.addSuppressed(new Throwable("Hesdfllo"));
throwable.addSuppressed(new Throwable("Hellso"));
System.out.println(anyMatch(throwable, t -> t.getMessage().contains("Hello"))); // false
throwable.addSuppressed(new Throwable("Hello"));
System.out.println(anyMatch(throwable, t -> t.getMessage().contains("Hello"))); // true
}
/**
* Returns {@code true} if {@code t} or its cause or t's supresses exceptions,
* recursively in the whole chain any {@linkplain Throwable} maches the given
* {@code predicate
*/
public static boolean anyMatch(Throwable t, Predicate<Throwable> predicate)
{
Throwable cause;
if (predicate.test(t) || ((cause = t.getCause()) != null) && anyMatch(cause, predicate))
return true;
for (Throwable supressed : t.getSuppressed())
if (anyMatch(supressed, predicate))
return true;
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment