Java tutorial
/* * Copyright (c) 2007 NTT DATA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jp.terasoluna.fw.util; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * ?? * * <p> * ???????<br> * ?????????? * ????? * ??????????? * ?????????? * * <strong>ExceptionUtil?</strong><br> * <code><pre> * * try { * * } catch (Exception e) { * // ?? * log.error("error-message", ExceptionUtil.getStackTrace(e)); * } * * </pre></code> * </p> * */ public final class ExceptionUtil { /** * */ private static Log log = LogFactory.getLog(ExceptionUtil.class); /** * ServletException??????????? * ??????? */ private static final String SERVLET_EXCEPTION_NAME = "javax.servlet.ServletException"; /** * ServletException??????? * Servlet ?????????????? */ private static final String GET_ROOT_CAUSE = "getRootCause"; /** * ????? * * <p> * ?????????????? * ???????? * ???getRootCause()????????ServletException?? * </p> * * @param throwable * @return ??? */ 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()); //throwable?Class?? Class<? extends Throwable> throwableClass = throwable.getClass(); // ServletException ?? getRootCause ? if (SERVLET_EXCEPTION_NAME.equals(throwableClass.getName())) { try { //throwable = ((ServletException) throwable).getRootCause() //Class?????? 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(); } }