• spring boot快速入门 8: 异常处理


    异常处理简单样例:

    第一步:创建result实体类

    package com.payease.domain;
    
    /**
     * http请求返回的最外层对象
     * Created by liuxiaoming on 2017/11/7.
     */
    public class Result<T> {
    
        /** 错误码 */
        private Integer code;
    
        /** 提示信息 */
        private String msg;
    
        /** 具体内容 */
        private T data;
    
        public Integer getCode() {
            return code;
        }
    
        public void setCode(Integer code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    
        public T getData() {
            return data;
        }
    
        public void setData(T data) {
            this.data = data;
        }
    }

    第二步:创建resultUtil工具类

    package com.payease.utils;
    
    import com.payease.domain.Result;
    
    /**
     * 对于结果集(Result)的工具类
     * Created by liuxiaoming on 2017/11/7.
     */
    public class ResultUtil {
        public static Result success(Object object){
            Result result = new Result();
            result.setCode(0);
            result.setMsg("成功");
            result.setData(object);
            return result;
        }
    
        public static Result success(){
            return success(null);
        }
    
        public static Result error(Integer code,String msg){
            Result result = new Result();
            result.setCode(code);
            result.setMsg(msg);
            return result;
        }
    
    }

    第三步:在controller中调用

    @Autowired
        private GirlRespository girlRespository;
       
     /**
         * 创建一个女生
         */
        @PostMapping("/girls")
        public Result<Girl> girlAdd(@Valid Girl girl, BindingResult bindingResult){
            Result result = new Result();
            if(bindingResult.hasErrors()){
                return ResultUtil.error(1,bindingResult.getFieldError().getDefaultMessage());
            }
            girl.setCupSize(girl.getCupSize());
            girl.setAge(girl.getAge());
            return ResultUtil.success(girlRespository.save(girl));
        }

    第四步:启动项目 在postman中提交请求

    请求成功:

    请求失败:

    样例:统一异常处理

     第一步:创建枚举类ResultEnum(统一管理错误码和错误信息)

    package com.payease.enums;
    
    /**
     * Created by liuxiaoming on 2017/11/7.
     */
    public enum ResultEnum {
        UNKNOWN_ERROR(-1, "未知错误"),
        SUCCESS(0, "成功"),
        PRIMARY_SCHOOL(100,"你可能还在上小学"),
        MIDDLE_SCHOOL(101,"你可能在上初中"),
    
        ;
    
    
        private Integer code;
        private String msg;
    
        ResultEnum(Integer code, String msg){
            this.code = code;
            this.msg = msg;
        }
    
        public Integer getCode() {
            return code;
        }
    
        public void setCode(Integer code) {
            this.code = code;
        }
    
        public String getMsg() {
            return msg;
        }
    
        public void setMsg(String msg) {
            this.msg = msg;
        }
    }

    第二步:创建自定义异常捕获类ExceptionHandle

    package com.payease.handle;
    
    import com.payease.domain.Result;
    import com.payease.enums.ResultEnum;
    import com.payease.exception.GirlException;
    import com.payease.utils.ResultUtil;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    /**
     * 自定义异常捕获类
     * Created by liuxiaoming on 2017/11/7.
     */
    @ControllerAdvice
    public class ExceptionHandle {
    
        //日志
        private final static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);
    
        @ExceptionHandler(value = Exception.class)
        @ResponseBody
        public Result handle(Exception e){
            if(e instanceof GirlException){
                GirlException girlException = (GirlException)e;
                return ResultUtil.error(girlException.getCode(),girlException.getMessage());
            }else{
                logger.info("【系统异常】{}",e);
                return ResultUtil.error(ResultEnum.UNKNOWN_ERROR.getCode(),ResultEnum.UNKNOWN_ERROR.getMsg());
                //return ResultUtil.error(-1,"未知错误:");
            }
    
        }
    }

    第三步:创建自定义异常类

    package com.payease.exception;
    
    import com.payease.enums.ResultEnum;
    
    /**
     * 自定义异常
     * Created by liuxiaoming on 2017/11/7.
     */
    public class GirlException extends RuntimeException{
    
        private Integer code;
    
        public GirlException(ResultEnum resultEnum) {
            super(resultEnum.getMsg());
            this.code = resultEnum.getCode();
        }
    
        public Integer getCode() {
            return code;
        }
    
        public void setCode(Integer code) {
            this.code = code;
        }
    }

    第四步:在service中添加方法

     public void getAge(Integer id) throws Exception{
            Girl girl = girlRespository.findOne(id);
            Integer age = girl.getAge();
            if(age < 10){
                //返回 "你还在上小学吧" code=100
                throw new GirlException(ResultEnum.PRIMARY_SCHOOL);
            }else if(age > 10 && age < 16){
                //返回 "你可能在上初中" code=101
                throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
            }
            //如果>16岁,加钱
            //...
        }

    第五步:在controller中调用该方法

        /**
         * 通过ID判断该女生年龄是否符合要求
         * @param id
         * @throws Exception
         */
        @GetMapping("girls/getAge/{id}")
        public void getAge(@PathVariable("id")Integer id) throws Exception{
    
             girlService.getAge(id);
        }

    第六步:启动项目 postman提交

  • 相关阅读:
    Android Html处理器通用类 HtmlUtil
    Android 文件管理器通用类 FileUtil
    Android 本应用数据清除管理器DataCleanManager
    获取索引--------用range()和len()
    循环结构中-------简单的部分放在上面, 条理会更清晰~~~ != 不等于
    列表 ->join---> 字符串 转类型:x--->y类型 y(x)
    迭代 判断数字 累加器
    print in或者not in, 判断在不在里面
    n=n+1 放在print(s)的上面的影响 (2) n=n=+1在前面,则不满足前面<100条件时候,才跳出while的循环,这时候while循环结束, 到了外面的下一步-->print()
    n=n+1 放在print(s)的前/后的影响
  • 原文地址:https://www.cnblogs.com/liuxiaoming123/p/7800285.html
Copyright © 2020-2023  润新知