using QYZH.InteractiveMagazine.Models.Dto;
namespace QYZH.InteractiveMagazine.Models.Common;
///
/// 业务异常类
///
public class BusinessException : Exception
{
///
/// 错误码
///
public int Code { get; set; }
///
/// 业务状态码
///
public ResultCode ResultCode { get; set; } = ResultCode.FAIL;
///
/// 无参构造函数
///
public BusinessException() : base()
{
}
///
/// 构造函数
///
/// 异常消息
public BusinessException(string message) : base(message)
{
}
///
/// 构造函数
///
/// 异常消息
/// 错误码
public BusinessException(string message, int code) : base(message)
{
Code = code;
ResultCode = System.Enum.IsDefined(typeof(ResultCode), code) ? (ResultCode)code : ResultCode.FAIL;
}
///
/// 构造函数(按业务状态码)
///
/// 异常消息
/// 业务状态码
public BusinessException(string message, ResultCode resultCode) : base(message)
{
ResultCode = resultCode;
Code = (int)resultCode;
}
///
/// 构造函数
///
/// 异常消息
/// 内部异常
public BusinessException(string message, Exception innerException) : base(message, innerException)
{
}
public static void ThrowIf(bool isTrue, string message)
{
if (isTrue) throw new BusinessException(message);
}
public static void ThrowIf(bool isTrue, Func action)
{
if (isTrue) throw new BusinessException(action.Invoke());
}
public static void ThrowIf(bool isTrue, string message, Action action)
{
if (isTrue)
{
action();
throw new BusinessException(message);
}
}
///
/// 条件抛出业务异常(带业务状态码)
///
/// 是否触发
/// 异常消息
/// 业务状态码
public static void ThrowIf(bool isTrue, string message, ResultCode resultCode)
{
if (isTrue) throw new BusinessException(message, resultCode);
}
}