第一步 定义一个接口 设置统一返回码
public interface RespCode {
Integer OK =20000;
Integer ERROR =20001;
}
第二步 定义一个统一格式的返回类(包含状态码,返回状态,返回消息,返回数据)
@Data
public class R {
private Integer code;
private boolean status;
private String message;
private Map<String,Object> data=new HashMap<>();
private R(){};
public static R ok(){
R r = new R();
r.code=RespCode.OK;
r.status=true;
r.message="成功";
return r;
}
public static R error(){
R r = new R();
r.code=RespCode.ERROR;
r.status=false;
r.message="失败";
return r;
}
public R message(String message){
this.message=message;
return this;
}
public R code(Integer code){
this.code=code;
return this;
}
public R data(String key, Object value){
this.data.put(key, value);
return this;
}
public R data(Map<String,Object> data){
this.data=data;
return this;
}
}
第三步 定义自定义异常类 继承RuntimeException 提供无参和有参构造
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomException extends RuntimeException {
private Integer code;
private String message;
}
第四步 注册全局异常类 引入 工具类 统一返回
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public R GlobalException(Exception e){
return R.error().message("执行了全局异常");
}
@ExceptionHandler(CustomException.class)
public R CustomException(CustomException e){
return R.error().code(e.getCode()).message(e.getMessage());
}
}
测试
//返回成功
R.ok()
//返回失败
R.error().message("自定义错误消息")
//返回数据 data
R.ok().data("data",data)
//捕获异常
try{
...
}catch(Exception e){
throw new CustomException(20001,”自定义异常消息“)
}