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 public final class ExceptionUtils
29 {
30 private ExceptionUtils()
31 {
32 }
33
34 /**
35 * <p>
36 * returns a list of all throwables (including the one you passed in) wrapped by the given throwable.
37 * In contrast to a simple call to <code>getClause()</code> on each throwable it will also check if
38 * the throwable class contain a method <code>getRootCause()</code> (e.g. ServletException or JspException)
39 * and call it instead.
40 * </p>
41 * <p>
42 * The first list element will your passed in exception, the last list element is the cause.
43 * </p>
44 */
45 public static List getExceptions(Throwable cause)
46 {
47 List exceptions = new ArrayList(10);
48 exceptions.add(cause);
49
50 do
51 {
52 Throwable nextCause;
53 try
54 {
55 Method rootCause = cause.getClass().getMethod("getRootCause", new Class[]{});
56 nextCause = (Throwable) rootCause.invoke(cause, new Object[]{});
57 }
58 catch(Exception e)
59 {
60 nextCause = cause.getCause();
61 }
62 if (cause == nextCause)
63 {
64 break;
65 }
66
67 if (nextCause != null)
68 {
69 exceptions.add(nextCause);
70 }
71
72 cause = nextCause;
73 }
74 while (cause != null);
75
76 return exceptions;
77 }
78
79 /**
80 * Find a throwable message starting with the last element.<p>
81 * Returns the first throwable message where <code>throwable.getMessage() != null</code> </p>
82 */
83 public static String getExceptionMessage(List throwables)
84 {
85 if (throwables == null)
86 {
87 return null;
88 }
89
90 for (int i = throwables.size()-1; i>0; i--)
91 {
92 Throwable t = (Throwable) throwables.get(i);
93 if (t.getMessage() != null)
94 {
95 return t.getMessage();
96 }
97 }
98
99 return null;
100 }
101 }