ExcptUtil.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * FileName:ExcptUtil.java
  3. * <p>
  4. * Copyright (c) 2017-2020, <a href="http://www.webcsn.com">hermit (794890569@qq.com)</a>.
  5. * <p>
  6. * Licensed under the GNU General Public License, Version 3 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. * <p>
  10. * http://www.gnu.org/licenses/gpl-3.0.html
  11. * <p>
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. */
  19. package cn.com.lzt.common.util;
  20. import java.io.PrintWriter;
  21. import java.io.StringWriter;
  22. /**
  23. * 功能:异常的工具类
  24. * @author xiongliang
  25. *
  26. * mobile enterprise application platform
  27. * Version 0.1
  28. */
  29. public class ExcptUtil {
  30. /**
  31. * 将CheckedException转换为UncheckedException.
  32. */
  33. public static RuntimeException unchecked(Throwable e) {
  34. if (e instanceof RuntimeException) {
  35. return (RuntimeException) e;
  36. } else {
  37. return new RuntimeException(e);
  38. }
  39. }
  40. /**
  41. * 将ErrorStack转化为String.
  42. */
  43. public static String getStackTraceAsString(Throwable e) {
  44. StringWriter stringWriter = new StringWriter();
  45. e.printStackTrace(new PrintWriter(stringWriter));
  46. return stringWriter.toString();
  47. }
  48. /**
  49. * 判断异常是否由某些底层的异常引起.
  50. */
  51. public static boolean isCausedBy(Throwable ex, Class<? extends Exception>... causeExceptionClasses) {
  52. Throwable cause = ex.getCause();
  53. while (cause != null) {
  54. for (Class<? extends Exception> causeClass : causeExceptionClasses) {
  55. if (causeClass.isInstance(cause)) {
  56. return true;
  57. }
  58. }
  59. cause = cause.getCause();
  60. }
  61. return false;
  62. }
  63. }