Mr. Cappuccino的第12杯咖啡——冒泡APP(升级版)之封装统一返回格式

冒泡APP(升级版)之封装统一返回格式

上篇博文介绍了bubble-common-base模块的主要作用(封装统一返回格式),这篇博文主要是对于该模块的工具类进行封装。

模块目录
Mr. Cappuccino的第12杯咖啡——冒泡APP(升级版)之封装统一返回格式_第1张图片

BaseApiResponse.java

package com.bubble.base;

import lombok.Data;
import lombok.ToString;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;

/**
 * @author honey
 * @date 2021-09-07 23:40:48
 */
@Data
@ToString
public final class BaseApiResponse<T> implements Serializable {

    private static final long serialVersionUID = 3406150521702449352L;

    private String code;
    private String msg;
    private T data;

    private BaseApiResponse() {

    }

    private BaseApiResponse(String code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private BaseApiResponse(BaseResultCode baseResultCode, T data, Object... params) {
        this.code = baseResultCode.getCode();
        if (params != null && params.length > 0) {
            this.msg = String.format(baseResultCode.getMsg(), params);
        } else {
            this.msg = baseResultCode.getMsg();
        }
        this.data = data;
    }

    public boolean isSuccess() {
        return BaseResultCode.SUCCESS.getCode().equals(this.code);
    }

    public boolean isNotSuccess() {
        return !isSuccess();
    }

    public static <T> BaseApiResponse<T> success(T data) {
        return new BaseApiResponse<>(BaseResultCode.SUCCESS, data);
    }

    public static <T> BaseApiResponse<T> success() {
        return success(null);
    }

    public static <T> BaseApiResponse<T> error(BaseResultCode baseResultCode) {
        return error(baseResultCode, null);
    }

    public static <T> BaseApiResponse<T> error(BaseResultCode baseResultCode, T data) {
        return new BaseApiResponse<>(baseResultCode, data);
    }

    public static <T> BaseApiResponse<T> error(BaseResultCode baseResultCode, T data, Object... params) {
        return new BaseApiResponse<>(baseResultCode, data, params);
    }

    public static <T> BaseApiResponse<T> error(String msg) {
        BaseResultCode unknown = BaseResultCode.UNKNOWN;
        if (StringUtils.isBlank(msg)) {
            return error(unknown);
        } else {
            return new BaseApiResponse<>(unknown.getCode(), msg);
        }
    }

}

BaseResultCode.java

package com.bubble.base;

/**
 * @author honey
 * @date 2021-09-08 00:04:49
 */
public enum BaseResultCode {

    /**
     * 统一返回码
     */
    SUCCESS("00000", "成功"),
    UNKNOWN("99999", "未知异常"),
    SYSTEM_EXCEPTION("B9999", "系统异常"),
    ;

    private final String code;
    private final String msg;

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

    public String getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }
}

这两个类主要对统一返回格式进行了一个封装,之后代码还会慢慢优化,小伙伴们如果有更好的建议可以积极留言哟,谢谢啦!

不怕在自己的梦想里跌倒,只怕在别人的奇迹中迷路。只做自己梦想的主人,不做别人奇迹的听众。

你可能感兴趣的:(Bubble,java,restful,mr)