SpringBoot之统一异常处理

xiaoxiao2021-02-28  32

前台返回参数

{"code":"", "msg":"", "data":"" }

1. 定义一个最外层的类

@Data public class Result<T> { //错误码 private Integer code; // 提示信息 private String msg; // 具体内容 private T data; }

2. 定义一个工具类

public static Result success(Object o) { Result result = new Result(); result.setCode(0); result.setMsg("成功"); result.setData(o); 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; }

3. 自定义一个异常类

@Data public class MyException extends RuntimeException { // 要继承RuntimeException而不是Exception, 因为spring框架只对RuntimeException才会回滚 private Integer code; public MyException(ResultEnum resultEnum) { // 这里注意下 super(resultEnum.getMsg()); this.code = resultEnum.getCode(); } }

4. 定义一个枚举类

@Getter public enum ResultEnum { SUCCESS(0, "成功"), UNKNOWN_ERROR(-1, "id小于10"), ; private Integer code; private String msg; ResultEnum(Integer code, String msg) { this.code = code; this.msg = msg; } }5. 测试搞定收工 public void getMyException(Integer id) throws Exception { if (id < 10) { throw new MyException(ResultEnum.UNKNOWN_ERROR); } }

引入了lombok插件

转载请注明原文地址: https://www.6miu.com/read-2625538.html

最新回复(0)