第一步封装返回统一格式:
import lombok.Data;
@Data
public class Result<T> {
private Integer code;
private String msg;
private T data;
}
第二步封装公共枚举:
/**
* @author liuXiangPeng
* @version 1.0.0
* @description 公共枚举接口
*/
public interface CommonEnum {
Number getCode();
String getMessage();
}
第三步封装ResultUtils:
import com.nh.schoolexam.schoolexam.enmus.ResultEnum;
import com.nh.schoolexam.schoolexam.vo.Result;
public class ResultUtils {
public static Result success(Object obj) {
return getResult(ResultEnum.SUCCESS, obj);
}
public static Result success() {
return getResult(ResultEnum.SUCCESS, null);
}
public static Result fail() {
return getResult(ResultEnum.FAIL, null);
}
public static Result getResult(ResultEnum re) {
return getResult(re, null);
}
public static Result getResult(ResultEnum re, Object obj) {
return getResult(re.getCode(), re.getMessage(), obj);
}
public static Result getResult(Integer code, String msg) {
return getResult(code, msg, null);
}
public static Result getResult(Integer code, String msg, Object obj) {
Result result = new Result();
result.setCode(code);
result.setMsg(msg);
result.setData(obj);
return result;
}
}
第四步封装返回参数:
public enum ResultEnum implements CommonEnum {
SUCCESS(200, "成功"),
UNVALID(3000, "用户未登录"),
UNAPPLY_POST(3010, "用户不存在或者密码错误"),
ERROR(5000, null);
private Integer code;
private String message;
ResultEnum(Integer code, String message) {
this.code = code;
this.message = message;
}
@Override
public Integer getCode() {
return code;
}
@Override
public String getMessage() {
return message;
}
}
第五步封装自定义异常:
@ControllerAdvice
@Slf4j
public class ExceptionHandle {
@ExceptionHandler(value = CustomException.class)
@ResponseBody
public Result handleVerificationCodeException(CustomException e){
log.error("【自定义异常】"+e.getLogInfo()+"\n{}",e);
return ResultUtils.getResult(e.getCode(),e.getMessage());
}
@ExceptionHandler(value = Exception.class)
@ResponseBody
public Result handleException(Exception e){
log.error("【系统异常】\n{}",e);
return ResultUtils.getResult(ResultEnum.ERROR.getCode(),"系统异常");
}
}
@Data
public class CustomException extends RuntimeException {
private static final long serialVersionUID = -4435837929656377189L;
private Integer code;
private String logInfo;
public CustomException(ResultEnum re, String logInfo) {
super(re.getMessage());
this.code = re.getCode();
this.logInfo = logInfo;
}
}
本文详细介绍了如何在Spring Boot应用中实现响应结果的统一格式化,包括封装返回对象、公共枚举、Util工具类、自定义异常处理等关键步骤。
1684

被折叠的 条评论
为什么被折叠?



