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

io.polaris.core.err.Exceptions Maven / Gradle / Ivy

There is a newer version: 3.2.1
Show newest version
package io.polaris.core.err;

import javax.annotation.Nonnull;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashSet;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @author Qt
 * @since 1.8
 */
public class Exceptions {


	public static  T of(Throwable t, Class type, Function builder) {
		if (t == null) {
			return builder.apply(t);
		}
		if (type.isAssignableFrom(t.getClass())) {
			return (T) t;
		}
		while (t.getCause() != null) {
			t = t.getCause();
			if (type.isAssignableFrom(t.getClass())) {
				return (T) t;
			}
		}
		return builder.apply(t);
	}

	public static  T of(Throwable t, Class type, Supplier builder) {
		if (t == null) {
			return builder.get();
		}
		if (type.isAssignableFrom(t.getClass())) {
			return (T) t;
		}
		while (t.getCause() != null) {
			t = t.getCause();
			if (type.isAssignableFrom(t.getClass())) {
				return (T) t;
			}
		}
		return builder.get();
	}

	public static Throwable getRootCauseUntil(@Nonnull Throwable t, Predicate predicate) {
		while (t.getCause() != null) {
			t = t.getCause();
			if (predicate.test(t)) {
				return t;
			}
		}
		return t;
	}

	public static Throwable getRootCause(@Nonnull Throwable t) {
		while (t.getCause() != null) {
			t = t.getCause();
		}
		return t;
	}

	public static Throwable getRootCauseSafely(@Nonnull Throwable t) {
		Set set = new HashSet<>();
		while (t.getCause() != null && !set.contains(t)) {
			set.add(t);
			t = t.getCause();
		}
		return t;
	}

	public static String getStackTrace(Throwable t) {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw, true);
		t.printStackTrace(pw);
		return sw.toString();
	}
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy