美文网首页Springboot
定义一个有用的 MyBaseException

定义一个有用的 MyBaseException

作者: 光剑书架上的书 | 来源:发表于2018-04-17 15:16 被阅读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;
        }
    }
    
    }
    

    相关文章

      网友评论

        本文标题:定义一个有用的 MyBaseException

        本文链接:https://www.haomeiwen.com/subject/yhxpkftx.html