java-spring返回类

状态码类:

public enum ServiceCode {

    OK(20000),
    ERR_BAD_REQUEST(40000),//错误请求
    ERR_NOT_FOUND(40400),//没有发现
    ERR_UNAUTHORIZED(40100),//未经授权
    ERR_UNAUTHORIZED_DISABLED(40110),//未经授权禁止
    ERR_FORBIDDEN(40300),//被禁止的
    ERR_CONFLICT(40900),//冲突
    ERR_INSERT(50000),//插入异常
    ERR_DELETE(50100),//删除异常
    ERR_UPDATE(50200),//更新异常
    ERR_SELECT(50300),//搜索异常
    ERR_JWT_EXPIRED(60000),//jwt过期
    ERR_JWT_MALFORMED(60100),//jwt格式不对
    ERR_JWT_SIGNATURE(60200),//jwl签名错误
    ERR_UNKNOWN(99999);//未知错误

    private Integer value;

    ServiceCode(Integer value) {
        this.value = value;
    }

    public Integer getValue() {
        return value;
    }

}

返回类:

/**
 * 统一的响应结果类型
 */
@Data  //依赖导入lombok
public class JsonResult implements Serializable {

    /**
     * 操作结果的状态码
     */
    @ApiModelProperty("业务状态码")
    private Integer state;
    /**
     * 操作“失败”时响应的提示文本
     */
    @ApiModelProperty("消息")
    private String message;
    /**
     * 操作“成功”时响应的数据
     */
    @ApiModelProperty("数据")
    private T data; // T=Type, E=Element, K=Key, V=Value。泛型

    public static JsonResult ok() {
        return ok(null);
    }


    public static  JsonResult ok(T data) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setState(ServiceCode.OK.getValue());
        jsonResult.setData(data);
        return jsonResult;
    }

    public static JsonResult fail(ServiceException e) {
        return fail(e.getServiceCode(), e.getMessage());
    }

    public static JsonResult fail(ServiceCode serviceCode, String message) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setState(serviceCode.getValue());
        jsonResult.setMessage(message);
        return jsonResult;
    }

}


    public static JsonResult fail(ServiceException e) {
        return fail(e.getServiceCode(), e.getMessage());
    }

    public static JsonResult fail(ServiceCode serviceCode, String message) {
        JsonResult jsonResult = new JsonResult();
        jsonResult.setState(serviceCode.getValue());
        jsonResult.setMessage(message);
        return jsonResult;
    }

}

(没有找到数据、不符合业务、查询失败等均抛出异常类,相当于if ···else···中的else情况)异常类:

/**
 * 业务异常
 */
public class ServiceException extends RuntimeException {

    private ServiceCode serviceCode;

    public ServiceException(ServiceCode serviceCode, String message) {
        super(message);
        this.serviceCode = serviceCode;
    }

    public ServiceCode getServiceCode() {
        return serviceCode;
    }

}

使用:

//成功情况,不带数据,只返回2000状态码
 public JsonResult 方法名(参数(可选))               
        return JsonResult.ok();
    }


//成功情况,带数据.T表示需要返回的数据类型,如:对象、list、string·····
 public JsonResult 方法名(参数(可选))               
       return  JsonResult.ok(T)

    }

//错误情况,ServiceCode.状态码。message为字符串
JsonResult jsonResult = JsonResult.fail(ServiceCode.状态码, message);
return jsonResult;

//或者抛异常
throw new ServiceException(ServiceCode.状态码, message);

你可能感兴趣的:(java,开发语言)