• Spring Boot 进阶之Web进阶 学习


    1.新建返回结果类 result.java

    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;
    }
    }

    2.自定义异常处理类 GirlException.java
    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;
    }

    }


    3.新建服务 GirlService.java 抛出异常
    public void getAge (Integer id) throws Exception{
    Girl girl = girlReposistory.findById(id).get();
    Integer age = girl.getAge();

    if(age<10){
    throw new GirlException(ResultEnum.PRIMARY_SCHOOL);  //定义枚举,统一管理
    }else if (age >10 && age <16){
    throw new GirlException(ResultEnum.MIDDLE_SCHOOL);
    }

    }

    4.controller类中调用girlService.getAge(id)方法,并抛出异常
    @GetMapping(value = "/getage/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception{
    girlService.getAge(id);

    }

    5.新建 ResultEnum.java枚举
    public enum ResultEnum {
    UNKONW_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 String getMsg() {
    return msg;
    }


    }
  • 相关阅读:
    微信小程序之----加载中提示框loading
    微信小程序之----消息提示框toast
    微信小程序之----弹框组件modal
    浅析浏览器的回流与重绘 (Reflow & Repaint)
    关于input的一些问题解决方法分享
    关于js中 toFixed()的一个小坑
    浅谈js中null和undefined的区别
    浅谈JS中的闭包
    浅谈JS中的浅拷贝与深拷贝
    css设置居中的方案总结
  • 原文地址:https://www.cnblogs.com/zhcnblog/p/8945843.html
Copyright © 2020-2023  润新知