5分钟学会springboot整合全局捕获异常

                                               springboot整合全局捕获异常

一、前言

       springboot整合全局捕获异常。

       在此记录下,分享给大家。

 二、springboot整合Mybatis

                                               

1、pom文件 依赖引入

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.8.RELEASE</version>
        <relativePath />
    </parent>

    <dependencies>
        <!-- SpringBoot 测试 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- SpringBoot web组件 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!-- 注解式 插入/构建/优雅代码 -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
        </dependency>
    </dependencies>

2、 application.yml - 不配置即可

3、GlobalExceptionHandler.java

/**
 * 全局异常捕获
 *      Handler
 * @author yys
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    // @ControllerAdvice 异常切面类
    // @ResponseBody 如想返回视图,去掉此注解即可

    /**
     * 全局运行时异常捕获
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String, Object> exceptionHandler(Exception ex) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        if(ex instanceof APIException) {
            map.put("errorCode", ((APIException) ex).getErrorCode());
            map.put("errorMsg", ((APIException) ex).getErrorMsg());
        } else {
            map.put("errorCode", 500);
            map.put("errorMsg", "系统错误");
        }
        System.err.println("错误位置:[" + ex.getStackTrace()[0] + "]");
        System.err.println("异常信息:[" + ex.getClass().getName() + "]");
        System.err.println("错误信息:[" + ex.getMessage() + "]");
        return map;
    }

}

4、APIException.java

/**
 * 自定义异常类
 *      Exception
 * @author yys
 */
@Data
public class APIException extends Exception {

    private static final long serialVersionUID = 1L;

    /**
     * errorCode:异常编码
     * errorMsg:异常描述
     * resolvedMsg:解决方法描述
     */
    private Integer errorCode;
    private String errorMsg;
    private String resolvedMsg;

    public APIException(Integer errorCode) {
        super("");
        this.errorCode = errorCode;
        this.errorMsg = "";
        this.resolvedMsg = "";
    }

    public APIException(Integer errorCode, String errorMsg) {
        super(errorMsg);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        this.resolvedMsg = "";
    }

    public APIException(Integer errorCode, String errorMsg, String resolvedMsg) {
        super(errorMsg);
        this.errorCode = errorCode;
        this.errorMsg = errorMsg;
        this.resolvedMsg = resolvedMsg;
    }

}

5、APIExceptionErrorCode.java

/**
 * 自定义异常错误编码
 *      Exception
 * @author yys
 */
public class APIExceptionErrorCode {
    
    /**
     * 系统参数异常编码
     *  建议以1开头
     */
    public enum SysError {

    	APP_KEY_ERROR(10000, "APP_KEY错误,可能为非法请求"),
    	SYS_PARAM_ERROR(10001, "系统参数不正确"),
    	TIME_EXPIRE_ERROR(10002, "系统时间差超过预设值,可能为非法请求"),
    	ACCESS_TOKEN_ERROR(10003, "ACCESS_TOKEN错误,可能为非法请求"),
    	ACCESS_TOKEN_EXPIRE(10004, "ACCESS_TOKEN已过期"),
    	SIGN_ERROR(10005, "签名验证不通过"),
    	NOT_EXIST(10006, "为必填项"),
    	TRANSFORM_ERROR(10007, "类型转换错误"),
    	SERVICE_ERROR(10008, "服务异常,请求不可达");

        private int code;
        private String message;

        private SysError(int code, String message) {
            this.code = code;
            this.message = message;
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

    }
    
    /**
     * 业务异常编码
     */
    public enum BizError {

    	/**
    	 * 公共业务异常================================================
    	 *  建议以9开头
    	 */
    	APP_KEY_NOT_EXIST(90001,"APP_KEY不存在"),
    	API_TYPE_NULL(90002, "请求接口类型为空"),
    	SPECIAL_CHARACTERS(90003, "上传路径存在特殊字符"),
    	BIZ_PARAM_ERROR(90004,"业务参数不正确"),
        DATA_NOT_BELONG_PRV(90005, "访问数据不属于此当前卖家"),
        FORM_DATA_IS_NULL(90006, "提交数据为空"),


    	/**
    	 * user业务异常================================================
    	 * 	建议以2开头
    	 */
        PROVIDER_NOT_EXIST(20001, "卖家不存在"),


    	/**
    	 * prod业务异常================================================
    	 * 	建议以3开头
    	 */
    	PROD_NOT_EXIST(30001, "商品不存在"),


        /**
    	 * order业务异常================================================
    	 * 	建议以4开头
    	 */
    	ORDER_NOT_EXIST(40002, "订单不存在");


        private int code;
        
        private String message;

        private BizError(int code, String message) {
            this.code = code;
            this.message = message;
        }

        public int getCode() {
            return code;
        }

        public void setCode(int code) {
            this.code = code;
        }

        public String getMessage() {
            return message;
        }

        public void setMessage(String message) {
            this.message = message;
        }

    }
    
}

6、YysControler.java

/**
 * 全局异常捕获测试
 *      Controller
 * @author yys
 */
@RestController
@RequestMapping("/test")
public class YysControler {

    /**
     * 系统异常测试
     * @return
     */
    @RequestMapping("/exception")
    public String exception() {
        int i = 1 / 0;
        return "success";
    }

    /**
     * 自定义异常测试
     * @return
     * @throws APIException
     */
    @RequestMapping("/apiException")
    public String apiException() throws APIException {
        throw new APIException(APIExceptionErrorCode.SysError.SYS_PARAM_ERROR.getCode(),
                APIExceptionErrorCode.SysError.SYS_PARAM_ERROR.getMessage());
    }

}

7、启动类

@SpringBootApplication
public class YysApp {

    public static void main(String[] args) {
        SpringApplication.run(YysApp.class, args);
    }

}

8、测试

http://localhost:8080/test/exception

  a、页面结果 - 如下图所示 :

                    

  b、控制台结果 - 如下图所示 : 

                      

http://localhost:8080/test/apiException

  a、页面结果 - 如下图所示 :

                     

  b、控制台结果 - 如下图所示 : 

                      

                       Now ~ ~ ~写到这里,就写完了,如果有幸帮助到你,请记得关注我,共同一起见证我们的成长

发布了74 篇原创文章 · 获赞 253 · 访问量 13万+

猜你喜欢

转载自blog.csdn.net/qq_42175986/article/details/103366182