• springBoot2.0 配置@ControllerAdvice 捕获异常统一处理


    一.前言

    基于上一篇 springBoot2.0 配置shiro实现权限管理

    这一篇配置 异常统一处理

    二.新建文件夹:common,param

    三.返回结果集对象

    1.ResultData.java

    package com.example.demo2.common;
    
    import lombok.Getter;
    import lombok.Setter;
    import lombok.ToString;
    
    import java.util.HashMap;
    import java.util.Map;
    
    /**
     * @author sssr
     * @version 1.0
     * @Description: 统一返回结果集对象
     * @date 2019/2/20
     */
    @Getter
    @Setter
    @ToString
    public class ResultData {
        private boolean ret;
        private String msg;
        private Object data;
    
        public ResultData() {
        }
    
        public ResultData(boolean ret){
            this.ret =ret;
        }
    
        public static ResultData success(Object data, String msg){
            ResultData resultData = new ResultData(true);
            resultData.data = data;
            resultData.msg = msg;
            return resultData;
        }
    
        public static ResultData success(Object data){
            ResultData resultData = new ResultData(true);
            resultData.data = data;
            return resultData;
        }
    
        public static ResultData success(){
            return new ResultData(true);
        }
    
    
        public static ResultData fail(String msg){
            ResultData resultData = new ResultData(false);
            resultData.msg = msg;
            return resultData;
        }
    
        public Map<String,Object> toMap(){
            HashMap<String,Object> result = new HashMap();
            result.put("ret",ret);
            result.put("msg",msg);
            result.put("data",data);
            return result;
        }
    }

     四.自定义全局异常类

    1.GlobalException.java

    package com.example.demo2.common;
    
    /**
     * @author sssr
     * @version 1.0
     * @Description: 自定义异常类
     * @date 2019/2/20
     */
    public class GlobalException extends RuntimeException{
        public GlobalException() {
        }
    
        public GlobalException(String message) {
            super(message);
        }
    
        public GlobalException(String message, Throwable cause) {
            super(message, cause);
        }
    
        public GlobalException(Throwable cause) {
            super(cause);
        }
    
        public GlobalException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
            super(message, cause, enableSuppression, writableStackTrace);
        }
    }

    五.异常捕获处理类

    1.GlobalExceptionResolver.java

    package com.example.demo2.common;
    
    import org.springframework.validation.BindException;
    import org.springframework.validation.FieldError;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.RestController;
    
    import java.io.UnsupportedEncodingException;
    import java.util.List;
    
    /**
     * @author sssr
     * @version 1.0
     * @Description: 异常捕获处理类
     * @date 2019/2/20
     */
    @ControllerAdvice
    @RestController
    public class GlobalExceptionResolver {
    
        /**
         * 全局异常处理
         * @param e
         * @return
         */
        @ExceptionHandler(Exception.class)
        public ResultData exception(Exception e){
            return ResultData.fail(e.getMessage());
        }
    
        /**
         * 自定义异常处理
         * @param e
         * @return
         */
        @ExceptionHandler(GlobalException.class)
        public ResultData globalException(Exception e){
            return ResultData.fail(e.getMessage());
        }
    
        /**
         * lombok请求参数不合法异常处理
         * @param e
         * @return
         * @throws UnsupportedEncodingException
         */
        @ExceptionHandler(BindException.class)
        public ResultData bindException(BindException e) throws UnsupportedEncodingException {
            e.printStackTrace();
            List<FieldError> fieldErrors = e.getFieldErrors();
            String errorMsg="{";
            for (FieldError fieldError:fieldErrors){
                errorMsg+=fieldError.getField()+":"+fieldError.getDefaultMessage()+",";
            }
            if(errorMsg.length()>1){
                errorMsg = errorMsg.substring(0,errorMsg.length()-1);
            }
            errorMsg+="}";
            return ResultData.fail(errorMsg);
        }
    }

    六.测试参数接收类

    1.TestParam.java

    package com.example.demo2.param;
    
    import lombok.Getter;
    import lombok.Setter;
    
    import javax.validation.constraints.NotBlank;
    import javax.validation.constraints.NotEmpty;
    import javax.validation.constraints.NotNull;
    import java.util.List;
    
    /**
     * @author sssr
     * @version 1.0
     * @Description:
     * @date 2019/2/20
     */
    @Getter
    @Setter
    public class TestParam {
        @NotBlank
        private String msg;
        @NotNull
        private Integer id;
        @NotEmpty
        private List<String> list;
    }

     七.测试控制器

     1.TestController.java

    package com.example.demo2.controller;
    
    import com.example.demo2.common.GlobalException;
    import com.example.demo2.param.TestParam;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.validation.Valid;
    
    /**
     * @author sssr
     * @version 1.0
     * @Description: 测试控制器
     * @date 2019/2/20
     */
    @RestController
    @RequestMapping("/test")
    public class TestController {
    
        @RequestMapping("/exception")
        public String exception() throws Exception {
    
            throw new Exception("全局错误");
    
        }
    
        @RequestMapping("/globalException")
        public String globalException() throws GlobalException {
    
            throw new GlobalException("自定义错误");
    
        }
    
        @RequestMapping("/bindException")
        public String bindException(@Valid TestParam testParam) {
    
            return testParam.getMsg();
        }
    }

    八.测试效果

     

     

  • 相关阅读:
    Flutter & Dart 安装在window系统
    HAWQ配置之客户端访问
    HAWQ配置之HDFS HA
    HAWQ集成Yarn HA作为资源管理服务
    ambari 安装HDP3.0.1后,启动服务的问题记录
    【Clojure 基本知识】小技巧s
    [转帖]Loading Data into HAWQ
    【Clojure 基本知识】 关于函数参数的各种高级用法
    【Clojure 基本知识】 ns宏的 指令(关键字) requrie的用法
    Linux系统解析域名的先后顺序【转帖】
  • 原文地址:https://www.cnblogs.com/qq1272850043/p/10408002.html
Copyright © 2020-2023  润新知