ExceptionUtil { public static String getStackTrace(Throwable throwable) { StringBuilder sb = new StringBuilder(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); while (throwable != null) { baos.reset(); throwable.printStackTrace(new PrintStream(baos)); sb.append(baos.toString()); Class<? extends Throwable> throwableClass = throwable.getClass(); if (SERVLET_EXCEPTION_NAME.equals(throwableClass.getName())) { try { Method method = throwableClass.getMethod(GET_ROOT_CAUSE); throwable = (Throwable) method.invoke(throwable); } catch (NoSuchMethodException e) { log.error(e.getMessage()); throwable = null; } catch (IllegalAccessException e) { log.error(e.getMessage()); throwable = null; } catch (InvocationTargetException e) { log.error(e.getMessage()); throwable = null; } } else { throwable = throwable.getCause(); } } return sb.toString(); }  static String getStackTrace(Throwable throwable);  }
@Test public void testGetStackTrace01() { NullPointerException ne = new NullPointerException(); String result = ExceptionUtil.getStackTrace(ne); assertTrue(result.indexOf("java.lang.NullPointerException") != -1); }
@Test public void testGetStackTrace02() { SystemException se = new SystemException(new ServletException(new NullPointerException())); String result = ExceptionUtil.getStackTrace(se); assertTrue( result.indexOf( "jp.terasoluna.fw.exception.SystemException") != -1); assertTrue(result.indexOf("\njavax.servlet.ServletException") != -1); assertTrue(result.indexOf("\njava.lang.NullPointerException") != -1); assertTrue( result.indexOf( "jp.terasoluna.framework.exception.SystemException") < result.indexOf("\njavax.servlet.ServletException")); assertTrue( result.indexOf( "\njavax.servlet.ServletException") < result.indexOf("\njava.lang.NullPointerException")); }
@Test public void testGetStackTrace03() { String trace = ExceptionUtil.getStackTrace(null); assertEquals("", trace); }