• 【转载】SpringBoot统一异常处理最佳实践


    写的真的好,掘金的质量真的高,实名点赞一波。

    https://juejin.im/post/5c3ea92a5188251e101598aa

    这是我之前写的统一响应结果集:

    public class ResponseResult {
    
        //状态码
        private int status;
    
        //消息
        private String message;
    
        //返回数据
        private Object data;
    
        public ResponseResult() {
        }
    
        public ResponseResult(int status, String message, Object data) {
            this.status = status;
            this.message = message;
            this.data = data;
        }
    
        //成功
        public static ResponseResult success(Object data){
            return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_SUCCESS,"success",data);
        }
    
        public static ResponseResult success(String message){
            return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_SUCCESS,message,null);
        }
    
        public static ResponseResult success(){
            return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_SUCCESS,"success",null);
        }
    
        //失败
        public static ResponseResult fail(){
            return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_FAIL,"fail",null);
        }
    
        public static ResponseResult fail(Object data){
            return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_FAIL,"fail",data);
        }
    
        public static ResponseResult fail(String message){
            return new ResponseResult(ResponseStatusConstant.RESPONSE_STATUS_FAIL,message,null);
        }
    
        public int getStatus() {
            return status;
        }
    
        public void setStatus(int status) {
            this.status = status;
        }
    
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        public Object getData() {
            return data;
        }
    
        public void setData(Object data) {
            this.data = data;
        }
    }

    常量定义:

    public interface ResponseStatusConstant {
    
        /**
         * 响应状态码,1表示成功
         */
        public static final int RESPONSE_STATUS_SUCCESS=1;
    
        /**
         * 响应状态码,2表示成功
         */
        public static final int RESPONSE_STATUS_FAIL=2;
    
        /**
         * 响应状态码,3表示没有权限
         */
        public static final int RESPONSE_STATUS_NO_PERMISSION=3;
    
    
    }

    总之,一定要面向切面(AOP)的思想。

  • 相关阅读:
    mongoDB
    邮箱认证
    Django中开启事务的两种方式
    总结
    __new__和__init__和__call__方法理解
    jupyter
    text()和html()区别
    django模型中auto_now和auto_now_add的区别
    ajax嵌套陷阱
    模板内置函数(HTML)
  • 原文地址:https://www.cnblogs.com/timetellu/p/12976639.html
Copyright © 2020-2023  润新知