定义一个有用的 MyBaseException
2018-04-17 本文已影响48人
光剑书架上的书
import java.util.ArrayList;
import java.util.List;
public class MyBaseException extends Exception {
public MyBaseException() {
super();
}
public MyBaseException(String message) {
super(message);
}
public MyBaseException(String message, Throwable cause) {
super(message, cause);
}
public MyBaseException(Throwable cause) {
super(cause);
}
public static String getStackMsg(Throwable e) {
StringBuffer sb = new StringBuffer();
StackTraceElement[] stackArray = e.getStackTrace();
sb.append(e.getClass().getName() + "\n");
for (int i = 0; i < stackArray.length; i++) {
StackTraceElement element = stackArray[i];
sb.append(element.toString() + "\n");
}
return sb.toString();
}
public static List<String> getStackMsgList(Throwable e) {
List<String> stringList = new ArrayList<>();
StackTraceElement[] stackArray = e.getStackTrace();
for (int i = 0; i < stackArray.length; i++) {
StackTraceElement element = stackArray[i];
stringList.add(
stackArray[i].getFileName() + "." +
stackArray[i].getClassName() + "." +
stackArray[i].getMethodName() + "." +
stackArray[i].getLineNumber()
);
}
return stringList;
}
}
@RequestMapping(value = "api")
@ResponseBody
public Result api() {
Result<List<MyDto>> result = new Result();
try {
result.setSuccess(true);
result.setData(api.getAll());
} catch (Exception e) {
result.setSuccess(false);
result.setMsg(MyBaseException.getStackMsgList(e));
}
return result;
}
class Result<T> {
T data;
boolean success = false;
List<String> msg;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public List<String> getMsg() {
return msg;
}
public void setMsg(List<String> msg) {
this.msg = msg;
}
}
}