ExceptionUtils.java 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package com.java110.utils.exception;
  2. import com.java110.utils.util.StringUtil;
  3. import org.springframework.util.ObjectUtils;
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6. import java.io.StringWriter;
  7. /**
  8. * Created by wuxw on 2018/4/14.
  9. */
  10. public class ExceptionUtils {
  11. public static Throwable resolveActualException(Throwable t)
  12. {
  13. Throwable cause = t;
  14. while (cause != null) {
  15. if (ObjectUtils.nullSafeClassName(cause).startsWith("com.java110.")) {
  16. return cause;
  17. }
  18. cause = cause.getCause();
  19. }
  20. return cause;
  21. }
  22. public static void rethrowException(Throwable t) {
  23. if ((t instanceof RuntimeException)) {
  24. throw ((RuntimeException)t);
  25. }
  26. throw new RuntimeException(t);
  27. }
  28. public static String populateExecption(Throwable t)
  29. {
  30. return populateExecption(t, 2000);
  31. }
  32. public static String populateExecption(Throwable t, int descLimit) {
  33. if (t != null) {
  34. String message = "";
  35. StringWriter writer = null;
  36. PrintWriter pw = null;
  37. try{
  38. writer = new StringWriter();
  39. pw = new PrintWriter(writer);
  40. t.printStackTrace(pw);
  41. message = writer.toString();
  42. } finally {
  43. if(pw != null) {
  44. pw.close();
  45. }
  46. if(writer != null) {
  47. try {
  48. writer.close();
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. }
  54. return StringUtil.truncateMessage(message, descLimit);
  55. }
  56. return null;
  57. }
  58. /**
  59. * 创建异常堆栈信息
  60. * @param message
  61. * @param cause
  62. * @return
  63. */
  64. public static String buildMessage(String message, Throwable cause) {
  65. if (cause != null) {
  66. StringBuilder buf = new StringBuilder();
  67. if (message != null) {
  68. buf.append(message).append("; ");
  69. }
  70. buf.append("nested exception is ").append(cause);
  71. return buf.toString();
  72. }
  73. else {
  74. return message;
  75. }
  76. }
  77. }