1 package fr.ifremer.quadrige3.core.exception;
2
3 /*-
4 * #%L
5 * Quadrige3 Core :: Quadrige3 Core Shared
6 * $Id:$
7 * $HeadURL:$
8 * %%
9 * Copyright (C) 2017 Ifremer
10 * %%
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Affero General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU Affero General Public License
22 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 * #L%
24 */
25
26
27 /**
28 * Helper class for exceptions
29 * Created by blavenie on 30/10/15.
30 */
31 public class Exceptions {
32
33
34 /**
35 * <p>getCause.</p>
36 *
37 * @param e a {@link java.lang.Throwable} object.
38 * @param classes a {@link java.lang.Class} object.
39 * @return a {@link java.lang.Throwable} object.
40 */
41 public static Throwable getCause(Throwable e, Class... classes) {
42 for (Class clazz: classes) {
43 if (clazz.isInstance(e)) {
44 return e;
45 }
46 }
47 if (e.getCause() != null) {
48 return getCause(e.getCause(), classes);
49 }
50 return null;
51 }
52
53 /**
54 * <p>hasCause.</p>
55 *
56 * @param e a {@link java.lang.Throwable} object.
57 * @param classes a {@link java.lang.Class} object.
58 * @return a boolean.
59 */
60 public static boolean hasCause(Throwable e, Class... classes) {
61 for (Class clazz : classes) {
62 if (clazz.isInstance(e)) {
63 return true;
64 }
65 }
66 return e.getCause() != null && hasCause(e.getCause(), classes);
67 }
68
69 @SuppressWarnings("unchecked")
70 public static <T extends Throwable> void rethrowInnerCauseIfExists(Throwable throwable, Class<T> causeClass) throws T {
71 T cause = (T) getCause(throwable, causeClass);
72 if (cause != null)
73 throw cause;
74 }
75 }