5.4 KiB
5.4 KiB
返回数据全局统一
- 首先定义格式化数据实体类
public class CommonResult<T> implements Serializable {
public static Integer CODE_SUCCESS = 0;
/**
* 错误码
*/
private Integer code;
/**
* 错误提示
*/
private String message;
/**
* 返回数据
*/
private T data;
/**
* 将传入的 result 对象,转换成另外一个泛型结果的对象
*
* 因为 A 方法返回的 CommonResult 对象,不满足调用其的 B 方法的返回,所以需要进行转换。
*
* @param result 传入的 result 对象
* @param <T> 返回的泛型
* @return 新的 CommonResult 对象
*/
public static <T> CommonResult<T> error(CommonResult<?> result) {
return error(result.getCode(), result.getMessage());
}
public static <T> CommonResult<T> error(Integer code, String message) {
Assert.isTrue(!CODE_SUCCESS.equals(code), "code 必须是错误的!");
CommonResult<T> result = new CommonResult<>();
result.code = code;
result.message = message;
return result;
}
public static <T> CommonResult<T> success(T data) {
CommonResult<T> result = new CommonResult<>();
result.code = CODE_SUCCESS;
result.data = data;
result.message = "";
return result;
}
@JsonIgnore // 忽略,避免 jackson 序列化给前端
public boolean isSuccess() { // 方便判断是否成功
return CODE_SUCCESS.equals(code);
}
@JsonIgnore // 忽略,避免 jackson 序列化给前端
public boolean isError() { // 方便判断是否失败
return !isSuccess();
}
public static Integer getCodeSuccess() {
return CODE_SUCCESS;
}
public static void setCodeSuccess(Integer codeSuccess) {
CODE_SUCCESS = codeSuccess;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
public class ServiceException extends RuntimeException{
/**
* 错误码
*/
private final Integer code;
public ServiceException(ServiceExceptionEnum serviceExceptionEnum) {
// 使用父类的 message 字段
super(serviceExceptionEnum.getMessage());
// 设置错误码
this.code = serviceExceptionEnum.getCode();
}
public Integer getCode() {
return code;
}
// ServiceExceptionEnum.java
public enum ServiceExceptionEnum {
// ========== 系统级别 ==========
SUCCESS(0, "成功"),
SYS_ERROR(2001001000, "服务端发生异常"),
MISSING_REQUEST_PARAM_ERROR(2001001001, "参数缺失"),
// ========== 用户模块 ==========
USER_NOT_FOUND(1001002000, "用户不存在"),
// ========== 订单模块 ==========
// ========== 商品模块 ==========
;
/**
* 错误码
*/
private int code;
/**
* 错误提示
*/
private String message;
ServiceExceptionEnum(int code, String message) {
this.code = code;
this.message = message;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
}
- 然后通过@RestControllerAdvice(basePackages = {"com.xiaoxiao.springboot2.controller"})拦截controller的返回response,统一处理返回值
// 此处增加basePackages配置,只拦截自有controller的返回值,不影响druid以及swagger的页面正常显示
@RestControllerAdvice(basePackages = {"com.xiaoxiao.springboot2.controller"})
public class CommonResultControllerAdvice implements ResponseBodyAdvice {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Override
public boolean supports(MethodParameter methodParameter, Class aClass) {
return true;
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if (o instanceof CommonResult){
return o;
}
return CommonResult.success(o);
}
/**
* 处理业务异常
* */
@ExceptionHandler(value = ServiceException.class)
public CommonResult serviceExceptionHandler(HttpServletRequest req, ServiceException ex){
return CommonResult.error(ex.getCode(),ex.getMessage());
}
/**
* 处理其他异常
* */
@ExceptionHandler(value = Exception.class)
public CommonResult exceptionHandler(HttpServletRequest req, Exception e) {
// 记录异常日志
logger.error("[exceptionHandler]", e);
// 返回 ERROR CommonResult
return CommonResult.error(ServiceException.ServiceExceptionEnum.SYS_ERROR.getCode(),
ServiceException.ServiceExceptionEnum.SYS_ERROR.getMessage());
}
}