Spring Boot Web 自定义返回值(通用)

在项目下新建common.entity包,包中包含两个文件Result数据类,ResultCode接口文件

Result.class

@Data
@NoArgsConstructor
public class Result {
    
    private Integer code;
    private String message;
    private Object data;

    
    /**
     * 请求成功的响应,不带查询数据(用于删除、修改、新增接口)
     * @param code
     */
    private Result(ResultCode code) {
        this.code = code.code;
        this.message = code.message;
    }

    /**
     * 请求成功的响应,带有查询数据(用于数据查询接口)
     * @param code
     * @param data
     */
    public Result(ResultCode resCode,Object data) {
        this.code = resCode.code;
        this.message = resCode.message;
        this.data = data;
    }


    public static Result SUCCESS(){
        return new Result(ResultCode.SUCCESS);
    }

    public static Result ERROR(){
        return new Result(ResultCode.SERVER_ERROR);
    }

    public static Result FAIL(){
        return new Result(ResultCode.FAIL);
    }
    
    public static Result FAIL_MSG(ResultCode resCode, String msg){
        return new Result(resCode.code,msg)
    }
}

ResultCode

package com.ihrm.common.entity;

public enum ResultCode {

    /**
     * SUCCESS:成功
     * FAIL:失败
     */
    SUCCESS(10000,"操作成功!"),
    //---系统错误返回码-----
    FAIL(10001,"操作失败"),
    UNAUTHENTICATED(10002,"您还未登录"),
    UNAUTHORISE(10003,"权限不足"),
    SERVER_ERROR(99999,"抱歉,系统繁忙,请稍后重试!");

    int code;
    String message;

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

    public int code() {
        return this.code;
    }

    public String message() {
        return this.message;
    }

}

枚举中错误码、包括其他字段的命名,可以根据自己需求更改,这里面只是举例。

另外推荐一个IDEA的插件,在搜索框输入alibaba即可看到Alibaba Java Code Guidelines插件。是阿里巴巴出的一个代码规范化的提示插件。
更多推荐访问https://www.cnblogs.com/gyyyblog/p/11979783.html

posted @ 2019-11-30 20:25  Gyyyang  阅读(733)  评论(0编辑  收藏  举报