一、前言
关于log4j2中log4j-core源码包org.apache.logging.log4j.core.util.Throwables异常处理类,通过获取主节点异常getRootCause方法、将异常堆栈内容按照行转换为字符串序列List<String>的toStringList方法,具体参见源码说明。
二、源码说明
package org.apache.logging.log4j.core.util;@b@@b@import java.io.IOException;@b@import java.io.InterruptedIOException;@b@import java.io.LineNumberReader;@b@import java.io.PrintWriter;@b@import java.io.StringReader;@b@import java.io.StringWriter;@b@import java.util.ArrayList;@b@import java.util.List;@b@@b@/**@b@ * Helps with Throwable objects.@b@ */@b@public final class Throwables {@b@@b@ private Throwables() {@b@ }@b@@b@ /**@b@ * Returns the deepest cause of the given {@code throwable}.@b@ *@b@ * @param throwable the throwable to navigate@b@ * @return the deepest throwable or the given throwable@b@ */@b@ public static Throwable getRootCause(final Throwable throwable) {@b@ Throwable cause;@b@ Throwable root = throwable;@b@ while ((cause = root.getCause()) != null) {@b@ root = cause;@b@ }@b@ return root;@b@ }@b@@b@ /**@b@ * Converts a Throwable stack trace into a List of Strings.@b@ *@b@ * @param throwable the Throwable@b@ * @return a List of Strings@b@ */@b@ public static List<String> toStringList(final Throwable throwable) {@b@ final StringWriter sw = new StringWriter();@b@ final PrintWriter pw = new PrintWriter(sw);@b@ try {@b@ throwable.printStackTrace(pw);@b@ } catch (final RuntimeException ex) {@b@ // Ignore any exceptions.@b@ }@b@ pw.flush();@b@ final List<String> lines = new ArrayList<>();@b@ final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));@b@ try {@b@ String line = reader.readLine();@b@ while (line != null) {@b@ lines.add(line);@b@ line = reader.readLine();@b@ }@b@ } catch (final IOException ex) {@b@ if (ex instanceof InterruptedIOException) {@b@ Thread.currentThread().interrupt();@b@ }@b@ lines.add(ex.toString());@b@ } finally {@b@ Closer.closeSilently(reader);@b@ }@b@ return lines;@b@ }@b@@b@ /**@b@ * Rethrows a {@link Throwable}.@b@ *@b@ * @param t the Throwable to throw.@b@ * @since 2.1@b@ */@b@ public static void rethrow(final Throwable t) {@b@ Throwables.<RuntimeException>rethrow0(t);@b@ }@b@@b@ @SuppressWarnings("unchecked")@b@ private static <T extends Throwable> void rethrow0(final Throwable t) throws T {@b@ throw (T) t;@b@ }@b@}