01: /*
02: * Copyright 2006 The Apache Software Foundation.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License");
05: * you may not use this file except in compliance with the License.
06: * You may obtain a copy of the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS,
12: * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13: * See the License for the specific language governing permissions and
14: * limitations under the License.
15: */
16: package org.apache.myfaces.shared_impl.util;
17:
18: import java.lang.reflect.Method;
19: import java.util.ArrayList;
20: import java.util.List;
21:
22: /**
23: * Various helpers to deal with exception
24: *
25: * @author imario@apache.org
26: */
27: public final class ExceptionUtils {
28: private ExceptionUtils() {
29: }
30:
31: /**
32: * <p>
33: * returns a list of all throwables (including the one you passed in) wrapped by the given throwable.
34: * In contrast to a simple call to <code>getClause()</code> on each throwable it will also check if the throwable class
35: * contain a method <code>getRootCause()</code> (e.g. ServletException or JspException) and call it instead.
36: * </p>
37: * <p>
38: * The first list element will your passed in exception, the last list element is the cause.
39: * </p>
40: */
41: public static List getExceptions(Throwable cause) {
42: List exceptions = new ArrayList(10);
43: exceptions.add(cause);
44:
45: do {
46: Throwable nextCause;
47: try {
48: Method rootCause = cause.getClass().getMethod(
49: "getRootCause", new Class[] {});
50: nextCause = (Throwable) rootCause.invoke(cause,
51: new Object[] {});
52: } catch (Exception e) {
53: nextCause = cause.getCause();
54: }
55: if (cause == nextCause) {
56: break;
57: }
58:
59: if (nextCause != null) {
60: exceptions.add(nextCause);
61: }
62:
63: cause = nextCause;
64: } while (cause != null);
65:
66: return exceptions;
67: }
68:
69: /**
70: * Find a throwable message starting with the last element.<br />
71: * Returns the first throwable message where <code>throwable.getMessage() != null</code>
72: */
73: public static String getExceptionMessage(List throwables) {
74: if (throwables == null) {
75: return null;
76: }
77:
78: for (int i = throwables.size() - 1; i > 0; i--) {
79: Throwable t = (Throwable) throwables.get(i);
80: if (t.getMessage() != null) {
81: return t.getMessage();
82: }
83: }
84:
85: return null;
86: }
87: }
|