1. 定义返回的统一对象

1
2
3
4
5
6
7
public class Result<T>{
private Integer code;
private String msg;
private T data;

//get和set方法;或者lombok的注解
}

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{
//spring 只会对runtimeException回滚
private Integer code;
//...省略get和set方法
public TestException(Integer code,String message){
super(message);
this.code = code;
}
}
1
2
3
4
5
//第三步添加
if(e instanceof TestException){
TestException ee = (TestException) e;//类型是我们自定义的话强转异常,通过get取值;
}

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;
}
//get方法
}

对应的自定义异常的构造方法,抛出异常等用到处可能也需要修改

6. 使用

在你需要的地方抛出异常即可,自定义异常也可实现多个构造方法满足相同业务场景下不同的需要

1
throw new TestException(200,"success");