zoukankan      html  css  js  c++  java
  • springboot json 异常统一处理,自定义异常处理

    参考:http://www.fengyunxiao.cn

    1. 建立 json 结果类,用于统一处理 json 结果

    public class JsonResult<T> {
        // code=0表示成功,返回数据data。data!=0,表示错误,返回错误信息msg
        private int code;
        // 若有错误,data不生成json
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private T data;
        // 若无错误,msg 不生成 json
        @JsonInclude(JsonInclude.Include.NON_NULL)
        private String msg;
    
        public JsonResult() {
            code = 0;
        }
    
        public JsonResult<T> ok(T data) {
            this.code = 0;
            this.data = data;
            return this;
        }
    
        public JsonResult<T> error(int code, String msg) {
            this.code = code;
            this.msg = msg;
            return this;
        }
    
        public T getData() {
            return data;
        }
    
        public void setData(T data) {
            this.data = data;
        }
    
        public int getCode() {
            return code;
        }
    
        public void setCode(int code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    }
    

    2. 建立自定义异常类

    public class CustemerException extends Exception {
        public CustemerException(String message) {
            super(message);
        }
    }
    

    3. 建立 rest controller 的异常抓捕类

    @RestControllerAdvice
    public class JsonExceptionHandler {
    
        @ExceptionHandler(value = Exception.class)
        public JsonResult<String> resolveException(HttpServletRequest request, HttpServletResponse response, Exception e) {
            JsonResult<String> result = new JsonResult<>();
            return result.error(1, e.getMessage());
        }
    
    }
    

    4. 在 rest controller的方法中抛出异常

    @Controller
    public class TestController {
    
        @RequestMapping("/test_error")
        public Object testError() throws Exception {
            if (true) {
                throw new CustemerException("抛出自定义异常");
            }
            return 1;
        }
    
    }
    

    5. 测试

    参考:http://www.fengyunxiao.cn

  • 相关阅读:
    Openjudge NOI题库 ch0111/01 查找最近的元素
    Openjudge NOI题库 ch0111/07 和为给定数
    Openjudge NOI题库 ch0111/08 不重复地输出数
    Openjudge NOI题库 ch0111/10 河中跳房子|NOIP2015 day2 stone
    Openjudge NOI题库 ch0111/t1776 木材加工
    SRM 508(2-1000pt)
    SRM 507(2-1000pt)
    SRM 504.5(2-1000pt)
    最小生成树专题总结
    SRM 506(2-1000pt)
  • 原文地址:https://www.cnblogs.com/zscc/p/9449974.html
Copyright © 2011-2022 走看看