de.thksystems.util.lang.ExceptionUtils Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of cumin Show documentation
Show all versions of cumin Show documentation
Commons for lang, crypto, xml, dom, text, csv, reflection, annotations, parsing, ...
/*
* tksCommons
*
* Author : Thomas Kuhlmann (ThK-Systems, http://www.thk-systems.de) License : LGPL (https://www.gnu.org/licenses/lgpl.html)
*/
package de.thksystems.util.lang;
import java.util.Optional;
import org.apache.commons.lang3.ClassUtils;
public final class ExceptionUtils {
private ExceptionUtils() {
}
/**
* Returns a {@link String} of the {@link Throwable} like:
*
*
* n.u.l.l.GeneralWorldFailure: You need to pray
* -> n.e.f.OrwellException: Big Brother is watching you
* -> abc.xyz.GoogleStillExistsException: null
*
*/
public static String getMessageList(Throwable t) {
StringBuffer sb = new StringBuffer();
Throwable throwable = t;
int depth = 0;
while (throwable != null) {
if (depth++ > 0) {
sb.append("\n").append("--> ");
}
sb.append(ClassUtils.getAbbreviatedName(throwable.getClass(), 25)).append(": ").append(throwable.getMessage());
throwable = throwable.getCause();
}
return sb.toString();
}
/**
* Returns true
, if the given {@link Throwable} or one of its causes {@link Class}es is assignable from the given {@link Class}.
*/
public static boolean isOfTypeOrHasCauseWithType(Throwable t, Class extends Throwable> expectedClass) {
Throwable throwable = t;
while (throwable != null) {
if (expectedClass.isAssignableFrom(throwable.getClass())) {
return true;
}
throwable = throwable.getCause();
}
return false;
}
/**
* Returns a causing exception or the exception itself, if it is of given type. (If any.)
*/
@SuppressWarnings("unchecked")
public static Optional getCauseWithType(Throwable t, Class expectedClass) {
for (Throwable throwable = t; throwable != null; throwable = throwable.getCause()) {
if (expectedClass.isAssignableFrom(throwable.getClass())) {
return (Optional) Optional.of(throwable);
}
}
return Optional.empty();
}
}