2008-06-09 18:36:05 +00:00
|
|
|
|
|
|
|
package net.sourceforge.tuned;
|
|
|
|
|
|
|
|
|
2009-02-09 20:56:20 +00:00
|
|
|
public final class ExceptionUtilities {
|
2008-06-09 18:36:05 +00:00
|
|
|
|
|
|
|
public static Throwable getRootCause(Throwable t) {
|
|
|
|
while (t.getCause() != null) {
|
|
|
|
t = t.getCause();
|
|
|
|
}
|
|
|
|
|
|
|
|
return t;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2009-05-02 23:34:04 +00:00
|
|
|
public static <T extends Throwable> T findCause(Throwable t, Class<T> type) {
|
|
|
|
while (t != null) {
|
|
|
|
if (type.isInstance(t))
|
2009-05-13 18:20:26 +00:00
|
|
|
return type.cast(t);
|
2009-05-02 23:34:04 +00:00
|
|
|
|
|
|
|
t = t.getCause();
|
|
|
|
}
|
|
|
|
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2009-02-10 21:51:02 +00:00
|
|
|
public static String getRootCauseMessage(Throwable t) {
|
|
|
|
return getMessage(getRootCause(t));
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public static String getMessage(Throwable t) {
|
|
|
|
String message = t.getMessage();
|
|
|
|
|
|
|
|
if (message == null || message.isEmpty()) {
|
2009-05-02 23:34:04 +00:00
|
|
|
message = t.toString();
|
2009-02-10 21:51:02 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return message;
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2009-05-12 08:57:37 +00:00
|
|
|
public static <T extends Throwable> T wrap(Throwable t, Class<T> type) {
|
|
|
|
if (type.isInstance(t)) {
|
2009-05-13 18:20:26 +00:00
|
|
|
return type.cast(t);
|
2008-06-09 18:36:05 +00:00
|
|
|
}
|
|
|
|
|
2009-05-12 08:57:37 +00:00
|
|
|
try {
|
|
|
|
return type.getConstructor(Throwable.class).newInstance(t);
|
|
|
|
} catch (Exception e) {
|
|
|
|
throw new IllegalArgumentException(e);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public static RuntimeException asRuntimeException(Throwable t) {
|
|
|
|
return wrap(t, RuntimeException.class);
|
2008-06-09 18:36:05 +00:00
|
|
|
}
|
|
|
|
|
2008-10-10 19:20:37 +00:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Dummy constructor to prevent instantiation.
|
|
|
|
*/
|
2009-02-09 20:56:20 +00:00
|
|
|
private ExceptionUtilities() {
|
2008-10-10 19:20:37 +00:00
|
|
|
throw new UnsupportedOperationException();
|
|
|
|
}
|
|
|
|
|
2008-06-09 18:36:05 +00:00
|
|
|
}
|