1. 定义返回的统一对象
1 2 3 4 5 6 7
| public class Result<T>{ private Integer code; private String msg; private T data;
}
|
2. ResultUtil
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| public class ResultUtil{ public static Result success(Object obj){ Result result = new Result(); result.setCode(0); result.setMsg("success"); result.setData(obj); return result; }
public static Result success(){ return success(null); }
public static Result success(Integer code,String msg){ Result result = new Result(); result.setCode(code); result.setMsg(msg); return result; } }
|
3. 异常捕获(ExceptionHandler)
1 2 3 4 5 6 7 8 9 10
| @ControllerAdvice public class ExceptionHandler{ @ExceptionHandler(value=Exception.class) @ResponseBody public Result handle(Exception e){ return ResultUtil.error(500,e.getMessage()); } }
|
4. 自定义异常类(****Exception)
1 2 3 4 5 6 7 8 9
| public class TestException extends RuntimeException{
private Integer code; public TestException(Integer code,String message){ super(message); this.code = code; } }
|
1 2 3 4 5
| if(e instanceof TestException){ TestException ee = (TestException) e; }
|
5. 枚举管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| public enum test{ UNKNOWN_ERROR(-1,"unknown"), SUCCESS(1,""), OTHER(100,"") ; private Integer code; private String msg; test(Integer code,String msg){ this.code = code; this.msg = msg; } }
|
对应的自定义异常的构造方法,抛出异常等用到处可能也需要修改
6. 使用
在你需要的地方抛出异常即可,自定义异常也可实现多个构造方法满足相同业务场景下不同的需要
1
| throw new TestException(200,"success");
|