114 lines
2.9 KiB
Java
114 lines
2.9 KiB
Java
package com.tailbet.common.exception;
|
||
|
||
import com.tailbet.common.enums.ErrorCodeEnum;
|
||
import lombok.Getter;
|
||
|
||
/**
|
||
* 业务异常
|
||
* <p>
|
||
* 封装业务逻辑层面的异常,区别于系统运行时异常。
|
||
* 业务异常通常有明确的错误码和提示信息,可直接返回给前端展示。
|
||
* 使用时优先使用预定义的错误码枚举,也支持自定义消息。
|
||
* </p>
|
||
*
|
||
* @author socialapp团队
|
||
* @since 1.0.0
|
||
*/
|
||
@Getter
|
||
public class BusinessException extends RuntimeException {
|
||
|
||
/**
|
||
* 错误码
|
||
*/
|
||
private final int code;
|
||
|
||
/**
|
||
* 附加数据(如当前场次信息等)
|
||
*/
|
||
private final Object data;
|
||
|
||
/**
|
||
* 基于错误码枚举构造业务异常
|
||
*
|
||
* @param errorCode 错误码枚举
|
||
*/
|
||
public BusinessException(ErrorCodeEnum errorCode) {
|
||
super(errorCode.getMessage());
|
||
this.code = errorCode.getCode();
|
||
this.data = null;
|
||
}
|
||
|
||
/**
|
||
* 基于错误码枚举和自定义消息构造业务异常
|
||
*
|
||
* @param errorCode 错误码枚举
|
||
* @param message 自定义错误消息
|
||
*/
|
||
public BusinessException(ErrorCodeEnum errorCode, String message) {
|
||
super(message);
|
||
this.code = errorCode.getCode();
|
||
this.data = null;
|
||
}
|
||
|
||
/**
|
||
* 基于错误码枚举、自定义消息和原因构造业务异常
|
||
*
|
||
* @param errorCode 错误码枚举
|
||
* @param message 自定义错误消息
|
||
* @param cause 原始异常
|
||
*/
|
||
public BusinessException(ErrorCodeEnum errorCode, String message, Throwable cause) {
|
||
super(message, cause);
|
||
this.code = errorCode.getCode();
|
||
this.data = null;
|
||
}
|
||
|
||
/**
|
||
* 基于状态码和自定义消息构造业务异常
|
||
*
|
||
* @param code 状态码
|
||
* @param message 错误消息
|
||
*/
|
||
public BusinessException(int code, String message) {
|
||
super(message);
|
||
this.code = code;
|
||
this.data = null;
|
||
}
|
||
|
||
/**
|
||
* 基于自定义消息构造业务异常(默认错误码 INTERNAL_ERROR)
|
||
*
|
||
* @param message 错误消息
|
||
*/
|
||
public BusinessException(String message) {
|
||
super(message);
|
||
this.code = ErrorCodeEnum.INTERNAL_ERROR.getCode();
|
||
this.data = null;
|
||
}
|
||
|
||
/**
|
||
* 基于错误码枚举和附加数据构造业务异常
|
||
* <p>
|
||
* 用于需要向前端返回额外数据的异常场景,
|
||
* 如 LIVE_ALREADY_ACTIVE 时携带已有场次信息。
|
||
* </p>
|
||
*
|
||
* @param errorCode 错误码枚举
|
||
* @param data 附加数据
|
||
*/
|
||
public BusinessException(ErrorCodeEnum errorCode, Object data) {
|
||
super(errorCode.getMessage());
|
||
this.code = errorCode.getCode();
|
||
this.data = data;
|
||
}
|
||
|
||
/**
|
||
* 获取对应的错误码枚举
|
||
*
|
||
* @return 错误码枚举
|
||
*/
|
||
public ErrorCodeEnum getErrorCodeEnum() {
|
||
return ErrorCodeEnum.of(this.code);
|
||
}
|
||
}
|