com.ideaaedi.commonds.exception.ExceptionUtil Maven / Gradle / Ivy
The newest version!
package com.ideaaedi.commonds.exception;
import com.ideaaedi.commonds.io.IOUtil;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* 异常工具类
*
* @author JustryDeng
* @since 1.0.0
*/
public class ExceptionUtil {
/**
* 将异常堆栈 信息 转换为字符串
*
* @param e
* 异常
* @return 该异常的错误堆栈信息
*/
public static String getStackTraceMessage(Throwable e) {
StringWriter sw = null;
PrintWriter pw = null;
try {
sw = new StringWriter();
pw = new PrintWriter(sw);
// 将异常的的堆栈信息输出到printWriter中
e.printStackTrace(pw);
pw.flush();
sw.flush();
return sw.toString();
} catch (Exception exception) {
throw new RuntimeException(exception);
} finally {
IOUtil.close(pw, sw);
}
}
/**
* 从异常链中直接寻找toSearchThrowable异常
*
* @param throwable 暴露异常(Nullable)
* @param toSearchThrowable 要寻找的异常(NonNull)
* @param depth 向下寻找深度(throwable本身不计数)
*
* @return 异常T (null-则表示未找到)
*/
public static T extractThrowable(Throwable throwable, Class toSearchThrowable, int depth) {
if (throwable == null) {
return null;
}
if (toSearchThrowable.isAssignableFrom(throwable.getClass())) {
return (T)throwable;
}
if (depth <= 0) {
return null;
}
Throwable cause = throwable.getCause();
T t = null;
for (int i = 0; i < depth; i++) {
if (cause == null) {
break;
}
if (toSearchThrowable.isAssignableFrom(cause.getClass())) {
t = (T)cause;
break;
}
cause = cause.getCause();
}
return t;
}
}