一、自定义全局返回包装类
/**
* @Description 统一结果集
*/
@Getter
@ToString
public class ResultSet<T> {
private Integer status; //状态码
private String codeMessage; //状态码信息
@Setter
private String errorMessage; //前后端对接错误信息
@Setter
private String errorMessageToUser; //给用户看的错误信息
private Date timestamp = new Date(); // 当前时间
@Setter
private T data; //响应数据
//私有构造器
private ResultSet() {
}
//响应成功,无响应数据
public static ResultSet<?> success() {
ResultSet<?> resultSet = new ResultSet<>();
resultSet.status = CodeEnum.SUCCESS.getCode();
resultSet.codeMessage = CodeEnum.SUCCESS.getCodeMessage();
return resultSet;
}
//响应成功,有响应数据
public static <T> ResultSet<T> success(T data) {
ResultSet<T> resultSet = new ResultSet<>();
resultSet.status = CodeEnum.SUCCESS.getCode();
resultSet.codeMessage = CodeEnum.SUCCESS.getCodeMessage();
resultSet.data = data;
return resultSet;
}
//响应失败(仅供异常处理器使用,其他地方建议均以抛出异常的方式响应)
public static ResultSet<?> error(CodeEnum codeEnum, String errorMessage, String errorMessageToUser) {
ResultSet<?> resultSet = new ResultSet<>();
resultSet.status = codeEnum.getCode();
resultSet.codeMessage = codeEnum.getCodeMessage();
resultSet.errorMessage = errorMessage;
resultSet.setErrorMessageToUser(errorMessageToUser);
return resultSet;
}
public static <T> ResultSet<T> custom(CodeEnum codeEnum, T data) {
ResultSet<T> resultSet = new ResultSet<>();
resultSet.status = codeEnum.getCode();
resultSet.codeMessage = codeEnum.getCodeMessage();
resultSet.data = data;
return resultSet;
}
}
二、拦截接口返回处理
//此注解针对controller层的类做增强功能,即对加了@RestController注解的类进行处理
/**
*此注解针对controller层的类做增强功能,即对加了@RestController注解的类进行处理
*/
@ControllerAdvice(annotations = RestController.class)
public class RestResponseBodyAdvice implements ResponseBodyAdvice<Object> {
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
ServerHttpResponse response) {
// 如果是通过Feign调用,不包装,直接返回
if (request.getHeaders().containsKey(Global.FEIGN)) {
return body;
}
//body为空
if(Objects.isNull(body)){
return ResultSet.success();
}
//为文件
if(body instanceof Resource){
return body;
}
//方法返回类型void
if (returnType.getMethod().getReturnType().isAssignableFrom(Void.TYPE)) {
return ResultSet.success();
}
//ResultSet||ResponseEntity直接返回
if((body instanceof ResultSet)||(body instanceof ResponseEntity)){
return body;
}
//处理string类型的返回值
//当返回类型是String时,用的是StringHttpMessageConverter转换器,无法转换为Json格式
//必须在方法体上标注RequestMapping(produces = "application/json; charset=UTF-8")
if (body instanceof String) {
return JsonUtils.obj2String(ResultSet.success(body));
}
//该方法返回的媒体类型是否是application/json。若不是,直接返回响应内容
if (!selectedContentType.includes(MediaType.APPLICATION_JSON)) {
return body;
}
return ResultSet.success(body);
}
}