1.统一状态码
@AllArgsConstructor
@Getter
public enum ResultEnum {
SUCCESS(200,"成功"),
ERROR(400,"失败");
private final Integer status;
private final String message;
}
2.统一返回结果
@Data
public class ResultVo {
private Boolean success;
private Integer status;
private String message;
private Map<String, Object> data = new HashMap<>();
private ResultVo(){}
public static ResultVo ok(){
ResultVo r = new ResultVo();
r.setSuccess(true);
r.setStatus(ResultEnum.SUCCESS.getStatus());
r.setMessage("成功");
return r;
}
public static ResultVo fail(){
ResultVo r = new ResultVo();
r.setSuccess(false);
r.setStatus(ResultEnum.ERROR.getStatus());
r.setMessage("失败");
return r;
}
public ResultVo success(Boolean success){
this.setSuccess(success);
return this;
}
public ResultVo message(String message){
this.setMessage(message);
return this;
}
public ResultVo status(Integer status){
this.setStatus(status);
return this;
}
public ResultVo data(String key, Object value){
this.data.put(key, value);
return this;
}
public ResultVo data(Map<String, Object> map){
this.setData(map);
return this;
}
}
3.使用
@RestController
public class UserController {
@GetMapping("/test")
public ResultVo test(){
return ResultVo.ok().status(200);
}
}