Exceptions.java
2.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.framework.util;
/*******************************************************************************
* Copyright (c) 2005, 2014 springside.github.io
*
* Licensed under the Apache License, Version 2.0 (the "License");
*******************************************************************************/
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* 关于异常的工具类.
*
* 参考了guava的Throwables。
*
* @author calvin
*/
@SuppressWarnings("all")
public class Exceptions {
/**
* 将CheckedException转换为UncheckedException.
*/
public static RuntimeException unchecked(Throwable ex) {
if (ex instanceof RuntimeException) {
return (RuntimeException) ex;
} else {
return new RuntimeException(ex);
}
}
/**
* 将ErrorStack转化为String.
*/
public static String getStackTraceAsString(Throwable ex) {
StringWriter stringWriter = new StringWriter();
ex.printStackTrace(new PrintWriter(stringWriter));
return stringWriter.toString();
}
/**
* 获取组合本异常信息与底层异常信息的异常描述, 适用于本异常为统一包装异常类,底层异常才是根本原因的情况。
*/
public static String getErrorMessageWithNestedException(Throwable ex) {
Throwable nestedException = ex.getCause();
return new StringBuilder().append(ex.getMessage()).append(" nested exception is ")
.append(nestedException.getClass().getName()).append(":").append(nestedException.getMessage())
.toString();
}
/**
* 获取异常的Root Cause.
*/
public static Throwable getRootCause(Throwable ex) {
Throwable cause;
while ((cause = ex.getCause()) != null) {
ex = cause;
}
return ex;
}
/**
* 判断异常是否由某些底层的异常引起.
*/
public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
Throwable cause = ex;
while (cause != null) {
for (Class<? extends Exception> causeClass : causeExceptionClasses) {
if (causeClass.isInstance(cause)) {
return true;
}
}
cause = cause.getCause();
}
return false;
}
}