老师,关于封装web返回对象

来源:2-5 封装Web返回对象

浅梦sky

2021-08-17

看了老师web返回对象,对于我个人来说可读性不好,于是我就自己写了一用于返回web对象,请老师看一下,我用自己写的这个替代老师写的R返回对象是否可以?请教下老师

@Data
public class ApiResponse<T> {
    // 业务状态码
    private Integer code;

    // 返回业务信息
    private String msg;

    // 返回业务数据
    private T data;

    // 正常的状态码200
    private static final int OK_CODE = HttpStatus.SC_OK;

    // 正常响应信息
    private static final String OK_MSG = "success";

    public ApiResponse() {
        this(OK_CODE, OK_MSG);
    }

    public ApiResponse(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public ApiResponse(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    // 不携带参数的返回,只返回code和msg,data为null
    public static <T> ApiResponse<T> ok() {
        return new ApiResponse<>();
    }

    public static <T> ApiResponse<T> ok(String msg) {
        ApiResponse<T> apiResponse = new ApiResponse<>();
        apiResponse.setMsg( msg );
        return apiResponse;
    }

    // 携带业务数据的成功返回
    public static <T> ApiResponse<T> ok(T result) {
        ApiResponse<T> apiResponse = new ApiResponse<>();
        apiResponse.setData( result );
        return apiResponse;
    }

    // 返回错误的信息
    public static <T> ApiResponse<T> error() {
        return new ApiResponse<>(HttpStatus.SC_INTERNAL_SERVER_ERROR, "未知异常,请联系管理员");
    }

    public static <T> ApiResponse<T> error(String msg) {
        return new ApiResponse<>(HttpStatus.SC_INTERNAL_SERVER_ERROR, msg);
    }
}


写回答

1回答

神思者

2021-08-17

我看过这种写法的封装,可以

0
1
浅梦sky
非常感谢!
2021-08-17
共1条回复

SpringBoot 在线协同办公小程序开发 全栈式项目实战

未来趋势型业务 + 前后端综合技术栈 + 惊艳的细节打磨

1798 学习 · 1915 问题

查看课程