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