服务器开发-对外接口返回数据-封装模板

服务器开发-对外接口返回数据-封装模板

96
天马行空LQ
1.3 2018.12.15 15:21* 字数 491 阅读 345 评论 0 赞赏 1

前言: 日常开发中我们一般都会做对外接口的统一数据返回模板,以下是我所采用的数据返回模板,分享出来目的是欢迎大家学习和帮助改进。

以下,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.*(..))")拦截到所有对外的接口方法。

  1. result = pjp.proceed();获取到拦截到的方法的返回数据报文。
  2. 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.cnblogs.com/jpfss/p/10724326.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值