View Javadoc
1   /**
2    * This file Copyright (c) 2009-2015 Magnolia International
3    * Ltd.  (http://www.magnolia-cms.com). All rights reserved.
4    *
5    *
6    * This file is dual-licensed under both the Magnolia
7    * Network Agreement and the GNU General Public License.
8    * You may elect to use one or the other of these licenses.
9    *
10   * This file is distributed in the hope that it will be
11   * useful, but AS-IS and WITHOUT ANY WARRANTY; without even the
12   * implied warranty of MERCHANTABILITY or FITNESS FOR A
13   * PARTICULAR PURPOSE, TITLE, or NONINFRINGEMENT.
14   * Redistribution, except as permitted by whichever of the GPL
15   * or MNA you select, is prohibited.
16   *
17   * 1. For the GPL license (GPL), you can redistribute and/or
18   * modify this file under the terms of the GNU General
19   * Public License, Version 3, as published by the Free Software
20   * Foundation.  You should have received a copy of the GNU
21   * General Public License, Version 3 along with this program;
22   * if not, write to the Free Software Foundation, Inc., 51
23   * Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
24   *
25   * 2. For the Magnolia Network Agreement (MNA), this file
26   * and the accompanying materials are made available under the
27   * terms of the MNA which accompanies this distribution, and
28   * is available at http://www.magnolia-cms.com/mna.html
29   *
30   * Any modifications to this file must keep this entire header
31   * intact.
32   *
33   */
34  package info.magnolia.cms.util;
35  
36  import org.apache.commons.lang3.StringUtils;
37  
38  /**
39   * Util to handle exceptions.
40   */
41  public class ExceptionUtil {
42  
43      /**
44       * Given a RuntimeException, this method will:
45       * - throw its cause exception, if the cause exception is an instance of the type of the unwrapIf parameter
46       * - throw its cause exception, if the cause exception is a RuntimeException
47       * - throw the given RuntimeException otherwise.
48       */
49      public static <E extends Throwable> void unwrapIf(RuntimeException e, Class<E> unwrapIf) throws E {
50          final Throwable wrapped = e.getCause();
51          if (unwrapIf != null && unwrapIf.isInstance(wrapped)) {
52              throw (E) wrapped;
53          } else if (wrapped != null && wrapped instanceof RuntimeException) {
54              throw (RuntimeException) wrapped;
55          } else {
56              throw e;
57          }
58      }
59  
60      /**
61       * This method helps palliating the absence of multi-catch (introduced in Java 7) - catch the lower common
62       * denominator exception and let this method do the rest - <strong>Use with great care!</strong>.
63       * <strong>Warning:</strong> this method can be abused, and would let one throw undeclared exceptions, which would
64       * in turn produce unexpected and undesirable effects on calling code. Just resist the urge to use this outside
65       * "multi-catch" scenarios.
66       */
67      public static void rethrow(Throwable e, Class<? extends Throwable>... allowedExceptions) {
68          if (RuntimeException.class.isInstance(e)) {
69              throw (RuntimeException) e;
70          }
71          for (Class<? extends Throwable> allowedException : allowedExceptions) {
72              if (allowedException.isInstance(e)) {
73                  sneakyThrow(e);
74              }
75          }
76          throw new Error("Caught the following exception, which was not allowed: ", e);
77      }
78  
79      /**
80       * Highly inspired by Lombok and the JavaPuzzlers, this method will let you throw a checked exception without declaring it.
81       * Use with GREAT care.
82       */
83      private static void sneakyThrow(Throwable t) {
84          ExceptionUtil.<RuntimeException>sneakyThrow_(t);
85      }
86  
87      @SuppressWarnings("unchecked")
88      private static <T extends Throwable> void sneakyThrow_(Throwable t) throws T {
89          throw (T) t;
90      }
91  
92      /**
93       * Returns true if the given exception or any of the nested cause exceptions is an instance of the <tt>suspectedCause</tt> exception argument, or a subclass thereof.
94       * This is equivalent to ExceptionUtils.indexOfThrowable(e, javax.jcr.AccessDeniedException.class) >= 0, only more readable, and possibly more performant.
95       */
96      public static boolean wasCausedBy(Throwable e, Class<? extends Throwable> suspectedCause) {
97          if (e != null && suspectedCause.isAssignableFrom(e.getClass())) {
98              return true;
99          } else if (e == null) {
100             return false;
101         } else {
102             return wasCausedBy(e.getCause(), suspectedCause);
103         }
104     }
105 
106     /**
107      * Translates an exception class name to an english-readable idiom. Example: an instance of AccessDeniedException will be returned as "Access denied".
108      */
109     public static String classNameToWords(Exception e) {
110         return classNameToWords((Throwable) e);
111     }
112 
113     public static String classNameToWords(Throwable e) {
114         return StringUtils.capitalize(StringUtils.removeEnd(e.getClass().getSimpleName(), "Exception").replaceAll("[A-Z]", " $0").toLowerCase().trim());
115     }
116 
117     /**
118      * Translates an exception class name to an english-readable idiom, along with the exception's message.
119      * Example: an instance of AccessDeniedException("/foo/bar") will be returned as "Access denied: /foo/bar".
120      */
121     public static String exceptionToWords(Exception e) {
122         return exceptionToWords((Throwable) e);
123     }
124 
125     public static String exceptionToWords(Throwable e) {
126         if (e.getMessage() != null) {
127             return classNameToWords(e) + ": " + e.getMessage();
128         } else {
129             return classNameToWords(e);
130         }
131     }
132 }