
name.remal.ThrowableUtils Maven / Gradle / Ivy
package name.remal;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.*;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static name.remal.UncheckedCast.uncheckedCast;
public class ThrowableUtils {
@NotNull
private static List<@NotNull T> findImpl(@NotNull Throwable rootThrowable, @NotNull Class type, boolean doReturnOnlyFirst) {
List result = null;
Set processedThrowables = new HashSet<>();
processedThrowables.add(rootThrowable);
Queue throwablesQueue = new LinkedList<>();
throwablesQueue.add(rootThrowable);
while (true) {
Throwable throwable = throwablesQueue.poll();
if (throwable == null) break;
if (type.isInstance(throwable)) {
if (doReturnOnlyFirst) return singletonList(uncheckedCast(throwable));
if (result == null) result = new ArrayList<>();
result.add(uncheckedCast(throwable));
}
{
Throwable cause = throwable.getCause();
if (cause != null && processedThrowables.add(cause)) throwablesQueue.add(cause);
}
for (Throwable supressed : throwable.getSuppressed()) {
if (processedThrowables.add(supressed)) throwablesQueue.add(supressed);
}
}
return result != null ? result : emptyList();
}
@NotNull
public static List<@NotNull T> findAll(@NotNull Throwable throwable, @NotNull Class type) {
return findImpl(throwable, type, false);
}
@Nullable
public static T findFirst(@NotNull Throwable throwable, @NotNull Class type) {
List list = findImpl(throwable, type, true);
return !list.isEmpty() ? list.get(0) : null;
}
@Nullable
public static T findLast(@NotNull Throwable throwable, @NotNull Class type) {
List list = findImpl(throwable, type, false);
return !list.isEmpty() ? list.get(list.size() - 1) : null;
}
public static boolean contains(@NotNull Throwable throwable, @NotNull Class extends Throwable> type) {
return findFirst(throwable, type) != null;
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy