1 17 18 package org.sape.carbon.core.exception; 19 20 import java.io.PrintWriter ; 21 import java.io.StringWriter ; 22 import java.lang.reflect.InvocationTargetException ; 23 import java.lang.reflect.Method ; 24 25 26 39 public class ExceptionUtility { 40 41 42 private static final Class [] GET_CAUSE_PARAMS = new Class [0]; 43 44 50 public static String printStackTracesToString(Throwable throwable) { 51 52 StringBuffer buf = new StringBuffer ( 53 ExceptionUtility.captureStackTrace(throwable)); 54 55 Throwable cause = ExceptionUtility.getNestedException(throwable); 56 if (cause != null) { 57 buf.append( 58 ExceptionUtility.printStackTracesToString(cause)); 59 } 60 return buf.toString(); 61 } 62 63 64 70 public static String captureStackTrace(Throwable throwable) { 71 if (throwable == null) { 72 return ""; 73 } else { 74 75 StringWriter sw = new StringWriter (); 76 throwable.printStackTrace(new PrintWriter (sw, true)); 77 78 return sw.toString(); 79 } 80 } 81 82 83 84 97 public static Throwable getNestedException(Throwable throwable) { 98 if (throwable == null) { 99 return null; 100 } 101 102 if (throwable instanceof InvocationTargetException ) { 103 return 104 ((InvocationTargetException ) throwable).getTargetException(); 105 106 } else if (throwable instanceof Exceptionable) { 107 return ((Exceptionable) throwable).getCause(); 108 } else { 109 try { 111 Class theClass = throwable.getClass(); 112 Method method = 113 theClass.getMethod("getCause", GET_CAUSE_PARAMS); 114 return (Throwable ) method.invoke(throwable, null); 115 } catch (Throwable t) { 116 return null; 118 } 119 } 120 } 122 123 124 } | Popular Tags |