赞
踩
**一些常用的返回状态码 **
https://help.aliyun.com/knowledge_detail/36393.html?spm=5176.10695662.1996646101.searchclickresult.33f71bb4EstSUR&aly_as=Gf1sQix
public interface Result<T> {
}
public enum StatusTypeEnum { /** * 200为成功 * 404为错误信息 */ SUCCESS(200,"success"), ERROR(404,"error"); private String msg; private int status; StatusTypeEnum(int status, String msg) { this.status = status; this.msg = msg; } }
@Data @AllArgsConstructor @NoArgsConstructor public class SuccessResult<T> implements Result<T> { private StatusTypeEnum status; private T data; public static SuccessResult succes() { return new SuccessResult<>(StatusTypeEnum.SUCCESS, null); } public static <T> SuccessResult succes(T data) { return new SuccessResult<>(StatusTypeEnum.SUCCESS, data); } }
@Data @NoArgsConstructor @AllArgsConstructor public class ErrorResult implements Result { private StatusTypeEnum status; private String msg; public static ErrorResult error(int status, Exception ex) { return new ErrorResult(StatusTypeEnum.ERROR, ex.getMessage()); } public static ErrorResult error() { return new ErrorResult(StatusTypeEnum.ERROR, "错误"); } }
定义的内容需要根据业务不同来定,这个只是大体架构
@RestControllerAdvice + 实现ResponseBodyAdvice
将Result 封装到aop 中, Controller层 直接返回 参数,让aop去判断,返回的Result
@RestControllerAdvice @Slf4j public class GlobalResultAdvice implements ResponseBodyAdvice { @Override public boolean supports(MethodParameter returnType, Class converterType) { log.error("supports"); //为false 将不执行下面的aop方法 return true; } /** * * @param body * @param returnType * @param selectedContentType * @param selectedConverterType * @param request * @param response * @return */ @Override public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) { Object resp = null; if (body instanceof SuccessResult){ resp = body; }else{ resp = SuccessResult.succes(body); } return resp; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。