SpringBoot2 自定义全局统一返回封装

# pom.xml
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>


# 枚举状态码定义

ResultCode.enum

import lombok.Getter;

/*
 * @author chenbz
 * @date 2020/09/23
 * @description: 全局统一返回响应枚举类
 * */
@Getter
public enum ResultCode {

    //1000系列通用错误
    SUCCESS(200, "操作成功"),
    WARNING(201, "操作失败"),
    FAILED(1001, "接口错误"),
    VALIDATE_FAILED(1002, "参数校验失败"),
    ERROR(500, "服务器内部错误"),

    //2000系列用户错误
    USER_NOT_EXIST(2000,"用户不存在"),
    USER_LOGIN_FAIL(2001,"用户名或密码错误"),
    USER_NOT_LOGIN(2002,"用户还未登录,请先登录"),
    NO_PERMISSION(2003,"权限不足,请联系管理员");

    private int code;
    private String msg;

    ResultCode(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }
}


# 实体类

Result.class

import lombok.Getter;
import lombok.Setter;

/*
 * @author chenbz
 * @date 2020/09/23
 * @description: 全局统一返回实体类
 * */
@Getter
@Setter
public class Result {
    private int code;
    private String msg;
    private Object data;
}


# 统一响应体定义

ResultResponse.class

/*
 * @author chenbz
 * @date 2020/09/23
 * @description: 自定义全局统一响应
 * */
public class ResultResponse {

    public static Result success() {
        return resultResponse(ResultCode.SUCCESS, "");
    }

    public static Result success(Object data) {
        return resultResponse(ResultCode.SUCCESS, data);
    }

    public static Result warning() {
        return resultResponse(ResultCode.WARNING, "");
    }

    public static Result warning(Object data) {
        return resultResponse(ResultCode.WARNING, data);
    }

    public static Result error() {
        return resultResponse(ResultCode.ERROR, "");
    }

    public static Result error(Object data) {
        return resultResponse(ResultCode.ERROR, data);
    }

    public static Result resultResponse(ResultCode resultCode, Object data) {
        return resultResponse(resultCode.getCode(), resultCode.getMsg(), data);
    }

    public static Result resultResponse(int code, String msg, Object data) {
        Result result = new Result();
        result.setCode(code);
        result.setMsg(msg);
        result.setData(data);

        return result;
    }
}


# 测试

TestController.class

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/test")
public class TestController {

    @GetMapping("/list")
    public Result list() {
        return ResultResponse.success();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值