Java 封装通用HTTP返回结果类

news/2024/7/24 8:45:55 标签: java, http, 网络

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();
    }


http://www.niftyadmin.cn/n/5279909.html

相关文章

“用户名不在 sudoers文件中,此事将被报告” 解决方法

原因 当普通用户需要安装文件时&#xff0c;无法用yum install ** -y直接安装时&#xff0c;采用sudo yum install **; 但是发现提示“用户名不在 sudoers文件中&#xff0c;此事将被报告” 解决方法。 这是因为该普通用户不在sudoers文件中&#xff0c;所以要找到该文件&am…

vue实现excel上传并显示数据

在vue中实现excel上传并显示数据 效果如下&#xff1a; vue--excel上传 具体代码如下&#xff1a; <template><div class"app-container"><inputref"excel-upload-input"class"excel-upload-input"style"width: 300px;mar…

行为型设计模式(三)状态模式 备忘录模式

状态模式 State 1、什么是状态模式 状态模式允许一个对象在其内部状态改变时改变它的行为&#xff0c;对象看起来似乎修改了它的类&#xff0c;将对象的行为包装在不同的状态类中&#xff0c;对象在运行时根据内部状态的改变而改变它的行为。 2、为什么使用状态模式 封装了…

第二证券:降息脚步渐近 银行板块估值望受提振

昨日&#xff0c;A股强势反弹&#xff0c;三大股指早盘探底回升&#xff0c;午后发力走高&#xff0c;深成指涨逾1%&#xff0c;创业板指一度涨超2%&#xff1b;北证50指数大幅回落&#xff0c;一度跌近8%&#xff1b;到收盘&#xff0c;沪指涨0.57%报2918.71点&#xff0c;深成…

认识YAML和Propertis

✅作者简介&#xff1a;大家好&#xff0c;我是Leo&#xff0c;热爱Java后端开发者&#xff0c;一个想要与大家共同进步的男人&#x1f609;&#x1f609; &#x1f34e;个人主页&#xff1a;Leo的博客 &#x1f49e;当前专栏&#xff1a; 循序渐进学SpringBoot ✨特色专栏&…

生活中的物理2——人类迷惑行为(用笔扎手)

1实验 材料 笔、手 实验 1、先用手轻轻碰一下笔尖&#xff08;未成年人须家长监护&#xff09; 2、再用另一只手碰碰笔尾 你发现了什么&#xff1f;&#xff1f; 2发现 你会发现碰笔尖的手明显比碰笔尾的手更痛 你想想为什么 3原理 压强f/s 笔尖的面积明显比笔尾的小 …

STM32F072 CAN and USB

1 通用描述 1.1 STM8 MOSTek 6502 -> ST7 -> STM8 STM8型号单片机分为STM8A、STM8L、STM8S三个系列。 STM8A&#xff1a;汽车级应用 STM8L&#xff1a;超低功耗MCU STM8S&#xff1a;标准系列 1.2 STM32 - F1系列用的最多&#xff0c;最大工作频率72MHz - STM32固件库&am…

灰度化、二值化、边缘检测、轮廓检测

灰度化 定义 灰度图像是只含亮度信息&#xff0c;不含色彩信息的图像。灰度化处理是把彩色图像转换为灰度图像的过程&#xff0c;是图像处理中的基本操作。OpenCV 中彩色图像使用 BGR 格式。灰度图像中用 8bit 数字 0&#xff5e;255 表示灰度&#xff0c;如&#xff1a;0 表…