验证中...
ApiResult
Raw Copy
public class ApiResult {
/**
* 错误码,对应{@link ErrorCode},表示一种错误类型
* 如果是成功,则code为200
*/
private int code;
/**
* 对错误的具体解释
*/
private String message;
/**
* 返回的结果包装在value中,value可以是单个对象
*/
private final Object value;
//忽略getter和setter,以及构造函数
}
ErrorCode
Raw Copy
public enum ErrorCode {
SUCCESS(200,"成功"),
NO_PERMISSION(211,"权限不足"),
SERVER_ERROR(10000,"服务器异常"),
AUTH_ERROR(10001,"认证失败"),
PARAMS_ERROR(10002,"参数错误"),
JSON_PARSE_ERROR(10003,"Json解析错误"),
ILLEAGAL_STRING(15001,"非法字符串"),
UNKNOW_ERROR(16000,"未知错误");
private int code;
private String msg;
ErrorCode(int code,String msg){
this.code = code;
this.msg = msg;
}
public int getCode() {
return code;
}
public String getMsg() {
return msg;
}
}
ApiResultHandler
Raw Copy
@ControllerAdvice(annotations = RestController.class)
public class ApiResultHandler implements ResponseBodyAdvice {
private ThreadLocal<ObjectMapper> mapperThreadLocal = ThreadLocal.withInitial(ObjectMapper::new);
private static final Class[] annos = {
RequestMapping.class,
GetMapping.class,
PostMapping.class,
DeleteMapping.class,
PutMapping.class
};
/**
* 对所有RestController的接口方法进行拦截
*/
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
AnnotatedElement element = returnType.getAnnotatedElement();
return Arrays.stream(annos).anyMatch(anno -> anno.isAnnotation() && element.isAnnotationPresent(anno));
}
@Override
public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
Object out;
ObjectMapper mapper = mapperThreadLocal.get();
response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
if(body instanceof ApiResult){
out = body;
}
else if (body instanceof ErrorCode){
ErrorCode errorCode = (ErrorCode) body;
out = new ApiResult(errorCode.getCode(),errorCode.getMsg(),null);
}
else if (body instanceof String){
ApiResult result = ApiResult.valueOf(body);
try {
//因为是String类型,我们要返回Json字符串,否则SpringBoot框架会转换出错
out = mapper.writeValueAsString(result);
} catch (JsonProcessingException e) {
out = ApiResult.errorOf(ErrorCode.JSON_PARSE_ERROR,e.getMessage());
}
}
else{
out = ApiResult.valueOf(body);
}
return out;
}
}

Comment list( 0 )

You need to Sign in for post a comment

Help Search