补充异常相关

This commit is contained in:
zk
2026-07-01 17:47:03 +08:00
parent 547cf21bf2
commit dfe7cca5a4
4 changed files with 265 additions and 27 deletions
+90
View File
@@ -0,0 +1,90 @@
"""业务断言工具类(风格参考 Spring Assert
使用方式:
from app.core.asserts import Assert
Assert.is_true(condition, "条件不满足的提示")
Assert.not_none(obj, "对象不能为空")
Assert.gt(days, 0, "天数必须大于0")
"""
from app.core.exceptions import AssertError
class Assert:
"""业务断言工具类
所有方法为静态方法,条件不满足时抛 AssertError(code=4100)。
"""
@staticmethod
def is_true(condition: bool, msg: str = "") -> None:
"""condition 为 False 时抛异常"""
if not condition:
raise AssertError(msg)
@staticmethod
def is_false(condition: bool, msg: str = "") -> None:
"""condition 为 True 时抛异常"""
if condition:
raise AssertError(msg)
@staticmethod
def not_none(obj, msg: str = "") -> None:
"""obj 为 None 时抛异常"""
if obj is None:
raise AssertError(msg)
@staticmethod
def is_none(obj, msg: str = "") -> None:
"""obj 不为 None 时抛异常"""
if obj is not None:
raise AssertError(msg)
@staticmethod
def has_text(text: str | None, msg: str = "") -> None:
"""text 为 None 或空字符串或纯空白时抛异常"""
if not text or not text.strip():
raise AssertError(msg)
@staticmethod
def not_empty(collection, msg: str = "") -> None:
"""集合/列表为 None 或空时抛异常"""
if not collection:
raise AssertError(msg)
@staticmethod
def gt(value, target, msg: str = "") -> None:
"""value <= target 时抛异常"""
if value <= target:
raise AssertError(msg)
@staticmethod
def gte(value, target, msg: str = "") -> None:
"""value < target 时抛异常"""
if value < target:
raise AssertError(msg)
@staticmethod
def lt(value, target, msg: str = "") -> None:
"""value >= target 时抛异常"""
if value >= target:
raise AssertError(msg)
@staticmethod
def lte(value, target, msg: str = "") -> None:
"""value > target 时抛异常"""
if value > target:
raise AssertError(msg)
@staticmethod
def eq(a, b, msg: str = "") -> None:
"""a != b 时抛异常"""
if a != b:
raise AssertError(msg)
@staticmethod
def ne(a, b, msg: str = "") -> None:
"""a == b 时抛异常"""
if a == b:
raise AssertError(msg)