服务器开发-对外接口返回数据-封装模板
前言: 日常开发中我们一般都会做对外接口的统一数据返回模板,以下是我所采用的数据返回模板,分享出来目的是欢迎大家学习和帮助改进。
以下,Enjoy:
DataResult.java(数据模板类):
/** * @Auther: 折戟沉沙 * @Description: 接口返回 数据模板 * @Version: 1.0 */ public class DataResult<T> { private String code; private String msg; private T body; /** * 默认处理成功,无需传入Code,Desc * @param body */ public DataResult(T body){ this.code = PlatStateCode.getByState("CD000001").getCode(); this.msg = PlatStateCode.getByState("CD000001").getDesc(); this.body = body; } public DataResult(String code, String msg) { this.code = code; this.msg = msg; } public DataResult(PlatStateCode platStateCode){ this.code = platStateCode.getCode(); this.msg = platStateCode.getDesc(); } public DataResult(PlatExceptionCode platExceptionCode){ this.code = platExceptionCode.getCode(); this.msg = platExceptionCode.getDesc(); } public DataResult(PlatStateCode platStateCode, T body){ this.code = platStateCode.getCode(); this.msg = platStateCode.getDesc(); this.body = body; } public DataResult(PlatExceptionCode platExceptionCode, T body){ this.code = platExceptionCode.getCode(); this.msg = platExceptionCode.getDesc(); this.body = body; } @Override public String toString() { return "ResultData{" + "code=" + code + ", body=" + body + ", msg='" + msg + '\'' + '}'; } public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getBody() { return body; } public void setBody(T body) { this.body = body; } }
PlatStateCode.java(平台状态码类):
/** * @Auther: 折戟沉沙 * @Description: 统一平台状态代码 * @Version:1.0 */ public enum PlatStateCode { /** 处理成功 */ SUCCESS("CD000001", "处理成功"), /** 处理中 */ PROCESSING("CD000002", "处理中"), /** 处理失败 */ FAILURE("CD000003", "处理失败"), ; private final String code; private final String desc; private PlatStateCode(String code, String desc) { this.code = code; this.desc = desc; } public String getCode() { return code; } public String getDesc() { return desc; } public static PlatStateCode getByState(String state) { if (state == null || state.length() == 0) { return null; } for (PlatStateCode each : values()) { if (state.equals(each.getCode())) { return each; } } return null; } @Override public String toString() { return "[" + code + ":" + desc + "]"; } }
PlatExceptionCode.java(平台错误状态码枚举类):
/** * @Auther: 折戟沉沙 * @Description: 平台代码错误枚举类 * @Version: 1.0 */ public enum PlatExceptionCode { /** 通用方法报错信息 */ FAILURE_REQ_URL("CD001001", "无效请求地址", PlatStateCode.FAILURE), ERR_OPER_TYPE("CD001002", "无效操作类型", PlatStateCode.FAILURE), FAILURE_REQ_PRM_NULL("CD001003", "请求参数不能为空", PlatStateCode.FAILURE), FAILURE_REQ_PRM_ERR("CD001004", "请求参数异常,请重试", PlatStateCode.FAILURE), FAILURE_REQ_LOGIN_OUT("CD001005", "登录超时,请重新登录", PlatStateCode.FAILURE), FAILURE_REQ_NOT_LOGIN("CD001006", "未登录,请登录操作", PlatStateCode.FAILURE), FAILURE_REQ_ERR("CD001007", "非法请求", PlatStateCode.FAILURE), ; private final String code; private final String desc; private final PlatStateCode state; PlatExceptionCode(String code, String desc, PlatStateCode state) { this.code = code; this.desc = desc; this.state = state; } public String getCode() { return code; } public String getDesc() { return desc; } public PlatStateCode getState() { return state; } public static PlatExceptionCode getByCode(String resCode) { if (resCode == null || resCode.length() == 0) { return null; } for (PlatExceptionCode each : values()) { if (each.getCode().equals(resCode)) { return each; } } return null; } @Override public String toString() { return "[" + code + ":" + desc + "]"; } }
如何使用?
使用AOP切面拦截对外接口,统一处理数据模板的封装
DataResultChange.java(数据模板AOP类):
/** * @Auther: 折戟沉沙 * @Description: 统一处理对外接口 数据模板 * @Version: 1.0 */ @Aspect @Component public class DataResultChange { private Logger logger = LoggerFactory.getLogger(DataResultChange.class); @Around("execution(* com.dofun.*..*Controller.*(..))") public Object logServiceAccess(ProceedingJoinPoint pjp) { Object result; try { result = pjp.proceed(); if (!(result instanceof DataResult)) result = new DataResult(result);// 默认成功,包装数据返回 } catch (Throwable e) { logger.error(e.getMessage(), e); //自定义业务异常 if (e instanceof ServiceException) { result = new DataResult(((ServiceException) e).getCode(), e.getLocalizedMessage()); } //表单验证异常 else if (e instanceof MethodArgumentNotValidException) { result = new DataResult(PlatExceptionCode.FAILURE_REQ_PRM_ERR); } //未知异常 else { result = new DataResult(PlatStateCode.FAILURE); } } return result; } }
DataResultChange类中通过@Around(“execution(* com.dofun...Controller.*(..))”)拦截到所有对外的接口方法。
- result = pjp.proceed();获取到拦截到的方法的返回数据报文。
- if (!(result instanceof DataResult))判断数据报文是否为我们定义的数据模板(DataResult),如果不是,则执行封装操作。
以上1、2步骤就是拦截到接口,数据返回正常的步骤。(一般来说只有处理成功状态才会执行try块)
那么在在日常开发中如何使用抛出异常呢?
第一步:自定义业务异常类
ServiceException.java(自定义业务异常类):
/** * @Auther: 折戟沉沙 * @Description: 业务通用异常 * @Version: 1.0 */ public class ServiceException extends RuntimeException{ private String code; public ServiceException(){} public ServiceException(String message){ super(message); } public ServiceException(String code,String message){ super(message); this.code = code; } /** * 平台错误代码枚举类 */ public ServiceException(PlatExceptionCode platExceptionCode){ super(platExceptionCode.getDesc()); this.code = platExceptionCode.getCode(); } /** * 平台状态代码枚举类 */ public ServiceException(PlatStateCode platStateCode){ super(platStateCode.getDesc()); this.code = platStateCode.getCode(); } public ServiceException(String message,Throwable e){ super(message,e); } public String getCode() { return code; } public void setCode(String code) { this.code = code; } }
第二步:代码中演示异常抛出
if (code.length() != 6) { logger.error("请求参数异常!code=" + code); throw new ServiceException(PlatExceptionCode.FAILURE_REQ_PRM_ERR); }
在实际代码逻辑中,我们遇到的异常都可以像以上方式直接抛出.
第三步:回顾DataResultChange.java中的catch中的异常处理逻辑
} catch (Throwable e) { logger.error(e.getMessage(), e); //自定义业务异常 if (e instanceof ServiceException) { result = new DataResult(((ServiceException) e).getCode(), e.getLocalizedMessage()); } //表单验证异常 else if (e instanceof MethodArgumentNotValidException) { result = new DataResult(PlatExceptionCode.FAILURE_REQ_PRM_ERR); } //未知异常 else { result = new DataResult(PlatStateCode.FAILURE); } }
在catch中,我们做了拦截ServiceException异常,然后封装数据模板的状态代码为传入的错误状态码。
注意点:
1.Controller采用的@RestController,会自动把所有方法的报文封装为Json格式,所以最终的DataResult数据模板返回出去是JSON格式。
{ "code": "CD000001", "msg": "处理成功", "body": { "ossPaths": "https://github.com" } }
2.Controller中方法返回类型必须为Object
@RestController @RequestMapping("/test") @Api(value = "演示-用户操作层",description = "用于-简书-代码演示") public class TestController { @RequestMapping(value = "/getOssPath/{code}",method = RequestMethod.GET) public Object getOssPath(@PathVariable("code") String code){ if (code.length() != 6) { logger.error("请求参数异常!code=" + code); throw new ServiceException(PlatExceptionCode.FAILURE_REQ_PRM_ERR); } return ossService.getOssPath(code);// 数据类型为 Map } }
以上便是服务器日常开发中,如何去封装对外接口的数据模板,谢谢阅读!
原文地址:https://www.jianshu.com/p/124dd90f015b
相关推荐
-
写好 Git Commit 信息的 7 个建议 服务器
2019-3-10
-
CentOS7.5二进制安装MySQL-5.6.40 服务器
2019-9-18
-
如何在 Linux 中重置 MySQL 或者 MariaDB 的 root 密码 服务器
2019-3-7
-
xtrabackup备份还原MySQL数据库 服务器
2019-7-8
-
换个角度聊聊FaaS 服务器
2019-5-25
-
sql server I/O硬盘交互 服务器
2019-5-22
-
对MySQL交换分区的实践 服务器
2020-5-31
-
linux中生成考核用的GPT分区表结构修复案例 服务器
2019-9-19
-
记一次centos网卡严重丢包现象(ethtool的使用) 服务器
2019-8-29
-
MySQL 处理插入过程中的主键唯一键重复值办法 服务器
2019-5-9