Spring Boot 2.x(六):优雅的统一返回结果

本文介绍了在Spring Boot 2.x中如何优雅地统一后端接口返回值,包括创建ReturnVO和ReturnCode枚举,使用AOP实现全局异常处理。通过配置ReturnVO,降低了代码重复度,简化了接口编写,同时展示了如何处理自定义异常,确保统一的错误信息返回。
摘要由CSDN通过智能技术生成

为什么要统一返回值

在我们做后端应用的时候,前后端分离的情况下,我们经常会定义一个数据格式,通常会包含codemessagedata这三个必不可少的信息来方便我们的交流,下面我们直接来看代码

ReturnVO

package indi.viyoung.viboot.util;

import java.util.Properties;

/**
 * 统一定义返回类
 *
 * @author yangwei
 * @since 2018/12/20
 */
public class ReturnVO {
   

    private static final Properties properties = ReadPropertiesUtil.getProperties(System.getProperty("user.dir") + "/viboot-common/src/main/resources/response.properties");

    /**
     * 返回代码
     */
    private String code;

    /**
     * 返回信息
     */
    private String message;

    /**
     * 返回数据
     */
    private Object data;


    public Object getData() {
   
        return data;
    }

    public void setData(Object data) {
   
        this.data = data;
    }

    public String getMessage() {
   
        return message;
    }

    public void setMessage(String message) {
   
        this.message = message;
    }

    public String getCode() {
   
        return code;
    }

    public void setCode(String code) {
   
        this.code = code;
    }

    /**
     * 默认构造,返回操作正确的返回代码和信息
     */
    public ReturnVO() {
   
        this.setCode(properties.getProperty(ReturnCode.SUCCESS.val()));
        this.setMessage(properties.getProperty(ReturnCode.SUCCESS.msg()));
    }

    /**
     * 构造一个返回特定代码的ReturnVO对象
     * @param code
     */
    public ReturnVO(ReturnCode code) {
   
        this.setCode(properties.getProperty(code.val()));
        this.setMessage(properties.getProperty
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值