假设要得到一个年龄分段的人,并做些其他处理,可以使用异常:

异常处理

在service里加个方法:抛出异常

public void getAge(Integer id) throws Exception {
        Men m = mp.getOne(id);
        if (m.getAge() < 10) {
            throw new Exception("还在上小学");
        } else if (m.getAge() < 16) {
            throw new Exception("可能在上初中");
        }
        // 其他事务......
    }

在controller里继续抛出:

@GetMapping("/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception {
        ms.getAge(id);
    }

然后新建一个ExceptionHandle类进行异常处理:

@ControllerAdvice
public class MenExpHandle {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<Object> handle(Exception e) {
        return ResultHelper.error(100, e.getMessage());
    }
}

现在访问试试:localhost:8080/men/getAge/1

{
  "code": 100,
  "msg": "还在上小学",
  "data": null
}
//id=3
{
  "code": 100,
  "msg": "可能在上初中",
  "data": null
}

但是可以看到不管是多少岁返回的code都是100,这对于调试不太好,所以我们自定义一个异常类。

自定义异常

public class MenException extends RuntimeException {
    private static final long serialVersionUID = 1L;
    private Integer code;

    public MenException(Integer code, String msg) {
        super(msg);
        this.code = code;
    }

    public Integer getCode() {
        return this.code;
    }
}

再修改异常处理:

public Result<Object> handle(Exception e) {
        if (e instanceof MenException) {
            MenException me = (MenException) e;
            return ResultHelper.error(me.getCode(), me.getMessage());
        }
        return ResultHelper.error(100, e.getMessage());
    }

和抛出地:

if (m.getAge() < 10) {
            throw new MenException(100, "还在上小学");
        } else if (m.getAge() < 16) {
            throw new MenException(101, "可能在上初中");
        }

结果可想而知。

改进错误代码

前面的code是自己随便写的,现在将其放在一个类里统一管理:

public enum ResultEnum {
    ERROR(-1, "系统错误"), OK(0, "OK"), OLD(10, "太老了"), YOUNG(11, "太年轻");

    private Integer code;
    private String msg;

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

然后使用:

if (m.getAge() < 10) {
            throw new MenException(ResultEnum.YOUNG);
        } else if (m.getAge() < 16) {
            throw new MenException(ResultEnum.OLD);
        }

需要修改类:

public MenException(ResultEnum e) {
        super(e.getMsg());
        this.code = e.getCode();
    }
public Result<Object> handle(Exception e) {
        if (e instanceof MenException) {
            MenException me = (MenException) e;
            return ResultHelper.error(me.getCode(), me.getMessage());
        } else {
            return ResultHelper.error(ResultEnum.ERROR);
        }
    }

结果:

{
  "code": 11,
  "msg": "太年轻",
  "data": null
}

results matching ""

    No results matching ""