All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.coditory.quark.context.Throwables Maven / Gradle / Ivy

There is a newer version: 0.1.22
Show newest version
package com.coditory.quark.context;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static com.coditory.quark.context.Args.checkNonNull;

final class Throwables {
    private Throwables() {
        throw new UnsupportedOperationException("Do not instantiate utility class");
    }

    @Nullable
    @SuppressWarnings("unchecked")
    public static  T getRootCauseOfType(Throwable throwable, Class type) {
        checkNonNull(throwable, "throwable");
        checkNonNull(type, "type");
        List list = getCauses(throwable);
        Collections.reverse(list);
        return list.stream()
                .filter(type::isInstance)
                .map(e -> (T) e)
                .findFirst()
                .orElse(null);
    }

    private static List getCauses(Throwable throwable) {
        checkNonNull(throwable, "throwable");
        List list = new ArrayList<>();
        Set visited = new HashSet<>();
        while (throwable != null && !visited.contains(throwable)) {
            list.add(throwable);
            visited.add(throwable);
            throwable = throwable.getCause();
        }
        return list;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy