zoukankan      html  css  js  c++  java
  • Spring/SpringBoot定义统一异常错误码返回

    配置

    大致说下流程,

    1. 首先我们自定义一个自己的异常类CustomException,继承RuntimeException。再写一个异常管理类ExceptionManager,用来抛出自定义的异常。

    2. 然后使用Spring提供的注解@RestControllerAdvice或者@ControllerAdvice写一个统一异常处理的类,在这个类中写一个带有@ExceptionHandler(Exception.class)注解的方法,这个方法会接收到所有抛出的异常,在方法内部我们就可以写自己的异常处理逻辑。

    3. 如果参数是CustomException类型,我们就自定义返回体,返回异常字典的错误信息。如果是其它类型的异常就返回系统异常。

    话不多说,上代码。

    一、自定义的异常类

    @Data
    @NoArgsConstructor
    public class CustomException extends RuntimeException {
    
        public CustomException(String code, String msg) {
            super(code);
            this.code = code;
            this.msg = msg;
        }
    
        private String code;
    
        private String msg;
    
    }

    二、异常管理类

    @Component
    public class ExceptionManager {
    
        @Resource
        Environment environment;
    
        public CustomException create(String code) {
            return new CustomException(code, environment.getProperty(code));
        }
    
    }

    Environment是spring的环境类,会包含所有properties文件的键值对。

    三、异常字典 exception.properties

    # sso异常测试
    EC00001=SSO的WEB层错误

    需要加载到spring的环境中,我是用配置类加载的,方式如下:

    @Component
    @PropertySource(value = {"exception.properties"}, encoding = "UTF-8")
    public class LoadProperty {
    
    }

    四、全局异常捕捉类

    @RestControllerAdvice
    public class GlobalExceptionHandler {
    
        @ExceptionHandler(Exception.class)
        public ApiResult handlerException(Exception e) {
    
            //如果是自定义的异常,返回对应的错误信息
            if (e instanceof CustomException) {
                e.printStackTrace();
                CustomException exception = (CustomException) e;
                return ApiResult.error(exception.getCode(), exception.getMsg());
            } else {
                //如果不是已知异常,返回系统异常
                e.printStackTrace();
                return ApiResult.error("SYS_EXCEPTION", "系统异常");
            }
    
        }
    
    }

    ApiResult是我处定义的接口json返回,代码也一并贴上.

    //ApiResult
    /**
     * @author kingboy--KingBoyWorld@163.com
     * @date 2017/7/23 下午7:19
     * @desc  返回体.
     */
    @Data
    public abstract class ApiResult {
    
        protected String code;
    
        /**
         * 成功的返回
         * @param data 数据
         * @return 正常返回体
         */
        public static ApiResult success(Object data) {
            return new SuccessApiResult(data);
        }
    
        /**
         * 错误返回
         * @param errorCode 错误码
         * @param errorMessage 错误信息
         * @return 错误返回体
         */
        public static ApiResult error(String errorCode, String errorMessage) {
            return new ErrorApiResult(errorCode, errorMessage);
        }
    
    
    }
    //SuccessApiResult
    @Data
    public class SuccessApiResult extends ApiResult {
    
        private Object data;
    
        SuccessApiResult(Object data) {
            this.code = "0";
            this.data = data;
        }
    
    }
    //ErrorApiResult
    @Data
    public class ErrorApiResult extends ApiResult {
    
        private String msg;
    
        ErrorApiResult(String code, String msg) {
            this.code = code;
            this.msg = msg;
        }
    }

    使用示例

    /**
     * @author kingboy--KingBoyWorld@163.com
     * @date 2017/8/1 下午5:57
     * @desc 异常测试.
     */
    @RestController
    @RequestMapping("/exception")
    public class ExceptionController {
    
        @Resource
        ExceptionManager exceptionManager;
    
        @RequestMapping("/controller")
        public String exceptionInController() {
            if (true) {
                throw exceptionManager.create("EC00001");
            }
            return "controller exception!";
        }
    
    }

    返回信息如下:

    {
        "code": "EC00001",
        "msg": "SSO的WEB层错误"
    }
  • 相关阅读:
    line-height:150%和line-height:1.5的区别
    javascript: with 表单验证
    CSS实现背景透明,文字不透明,兼容所有浏览器
    关于伪类元素:before和:after
    图片预览实例分享
    微信浏览器取消缓存的方法
    学习笔记(四):jQuery之动画效果
    学习笔记(三):jQuery之DOM
    Git 常用命令
    开发规范(三)数据库 By 阿里
  • 原文地址:https://www.cnblogs.com/toSeeMyDream/p/9530887.html
Copyright © 2011-2022 走看看