com.github.azbh111.utils.java.exception.ExceptionUtils Maven / Gradle / Ivy
Show all versions of utils-java Show documentation
package com.github.azbh111.utils.java.exception;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;
/**
* @author pyz
* @date 2019/3/30 11:17 AM
*/
public class ExceptionUtils {
public static String getStackTrace(Throwable throwable) {
StringWriter sw = new StringWriter();
throwable.printStackTrace(new PrintWriter(sw));
return sw.toString();
}
public static Throwable unwrap(Throwable e) {
if (e == null) {
return null;
}
Throwable pre = e;
Throwable unwrap;
while (true) {
unwrap = unwarpOnce(pre);
if (unwrap != null) {
pre = unwrap;
} else {
return pre;
}
}
}
public static T unwrap(Throwable e, Class upper) {
if (e == null) {
return null;
}
Throwable pre = e;
Throwable unwrap;
while (true) {
if (upper.isInstance(pre)) {
return (T) pre;
}
unwrap = unwarpOnce(pre);
if (unwrap == null) {
return null;
}
pre = unwrap;
}
}
/**
* so crazy!
*
* Throw checked exceptions like runtime exceptions.
*
* see: http://blog.jooq.org/2012/09/14/throw-checked-exceptions-like-runtime-exceptions-in-java/
*/
public static void throwException(Throwable e) {
ExceptionUtils.rethrow0(e);
}
private static Throwable unwarpOnce(Throwable e) {
Throwable unwrap;
if (e instanceof InvocationTargetException) {
unwrap = ((InvocationTargetException) e).getTargetException();
} else if (e instanceof UndeclaredThrowableException) {
return ((UndeclaredThrowableException) e).getUndeclaredThrowable();
} else if (e.getClass().getSimpleName().contains("Nested")) {
unwrap = e.getCause();
} else {
unwrap = null;
}
return unwrap;
}
@SuppressWarnings("unchecked")
private static void rethrow0(Throwable e) throws E {
throw (E) e;
}
}