Java 封装通用HTTP返回结果类

发布时间:2023年12月22日

1.返回结果类:

/**
 * 响应结果
 * @param <T>
 */
public class ResponseBean<T> {

    public ResponseBean() {

    }

    /**
     * 时间戳
     */
    @ApiModelProperty(value = "时间戳", name = "timestamp")
    private String timestamp = DateUtils.dateToStr(new Date(), DateUtils.YYYY_MM_DD_HH_MM_SS);

    /**
     * http 状态码
     */
    @ApiModelProperty(value = "http状态码", name = "code")
    private int code;

    /**
     * 返回信息
     */
    @ApiModelProperty(value = "返回信息", name = "msg")
    private String msg;

    /**
     * 返回的数据
     */
    @ApiModelProperty(value = "", name = "data")
    private T data;

    /**
     * 追踪Id
     */
    @ApiModelProperty(value = "追踪Id", name = "traceId")
    private String traceId;

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

    public ResponseBean(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 返回成功消息
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> success() {
        return ResponseBean.success(ResultCode.SUCCESS.getMsg());
    }

    /**
     * 返回成功消息
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> success(String msg) {
        return ResponseBean.success(msg, null);
    }

    public static <T> ResponseBean<T> success(T obj) {
        return ResponseBean.success(ResultCode.SUCCESS.getMsg(), obj);
    }

    /**
     * 返回成功消息
     * @param msg
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> success(String msg, T obj) {
        return ResponseBean.success(ResultCode.SUCCESS.getCode(), msg, obj);
    }

    /**
     * 返回成功消息
     * @param code
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> success(int code, String msg) {
        return ResponseBean.success(code, msg, null);
    }

    /**
     * 返回成功消息
     * @param code
     * @param msg
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> success(int code, String msg, T obj) {
        return new ResponseBean<T>(code, msg, obj);
    }

    /**
     * 失败平滑,服务降级
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> failover(String msg) {
        return ResponseBean.error(503, msg, null);
    }

    /**
     * 返回错误消息
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> error() {
        return ResponseBean.error(ResultCode.FAIL.getMsg());
    }

    /**
     * 返回错误消息
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> error(String msg) {
        return ResponseBean.error(msg, null);
    }

    /**
     * 返回错误消息
     * @param msg
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> error(String msg, T obj) {
        return ResponseBean.error(ResultCode.FAIL.getCode(), msg, obj);
    }

    /**
     * 返回错误消息
     * @param code
     * @param msg
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> error(int code, String msg) {
        return ResponseBean.error(code, msg, null);
    }

    /**
     * 返回错误消息
     * @param code
     * @param msg
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> ResponseBean<T> error(int code, String msg, T obj) {
        return new ResponseBean<T>(code, msg, obj);
    }

    public String getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(String timestamp) {
        this.timestamp = timestamp;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public T getData() {
        return data;
    }


    public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {
        if (isSuccess() && data != null) {
            return data;
        } else {
            throw exceptionSupplier.get();
        }
    }
    public  T orElseThrow()  {
        return this.orElseThrow(()->new BusinessException("第三方接口调用异常"));
    }

    public T orElseGet(Supplier<? extends T> other) {
        return isSuccess() && data != null ? data : other.get();
    }
    public void setData(T data) {
        this.data = data;
    }
    
    public String getTraceId() {
        return MDC.get("traceId");
    }

    public void setTraceId(String traceId) {
        this.traceId = traceId;
    }


    public Boolean isSuccess() {
        return this.code == 0;
    }

    public void notSuccessThrow(String msg) {
        if (this.code != 0) {
            throw new BusinessException(msg + ":" + getMsg());
        }
    }

    public void isDataNullThrow(String msg) {
        if (data == null) {
            throw new BusinessException(msg + ":返回为空");
        }
    }

    public void isDataNullThrow(String msg, Boolean func) {
        if (func) {
            throw new BusinessException(msg + ":返回为空");
        }
    }

}

2.结果枚举

public enum ResultCode {
	/**
	 * 失败
	 */
	FAIL(1, "请求失败"), 
	/**
	 * 成功
	 */
	SUCCESS(0, "请求成功");

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

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public int getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}
	
}

3.自定义业务异常类

public class BusinessException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    /**
     * 错误码
     */
    private Integer errorCode;

    public BusinessException() {
        super("业务异常", null, false, false);
    }

    public BusinessException(String errMsg) {
        super(errMsg, null, false, false);
    }

    public BusinessException(String errMsg, Integer errorCode) {
        super(errMsg, null, false, false);
        this.errorCode = errorCode;
    }


    public Integer getErrorCode() {
        return errorCode;
    }

    public void setErrorCode(Integer errorCode) {
        this.errorCode = errorCode;
    }

}

4.使用示例:

?4.1 返回成功消息

?返回成功消息,不携带参数

    @Override
    public ResponseBean add(xxx entity) {
        //业务逻辑
        return ResponseBean.success();
    }

返回成功消息,携带参数

    @Override
    public ResponseBean detail(xxx entity) {
        //业务逻辑
        return ResponseBean.success(entity);
    }

4.2?返回失败消息

    @Override
    @ApiOperation("新增")
    public ResponseBean add(xxx entity) {
        try {
            //业务逻辑
        } catch (Exception e) {
            
                return ResponseBean.error(e.getMessage());
            }
        }
        return ResponseBean.success();
    }

文章来源:https://blog.csdn.net/weixin_38860401/article/details/135155258
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。