53 lines
1.5 KiB
Python
53 lines
1.5 KiB
Python
"""统一异常体系。
|
|
|
|
业务代码只抛 BusinessError,由 main.py 里的处理器转成统一响应,
|
|
避免把 traceback 直接甩给前端。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
|
|
class BusinessError(Exception):
|
|
"""可预期的业务异常(参数不合法、状态不允许流转、数据不存在等)。"""
|
|
|
|
def __init__(self, msg: str, code: int = 400, data: Any = None) -> None:
|
|
self.msg = msg
|
|
self.code = code
|
|
self.data = data
|
|
super().__init__(msg)
|
|
|
|
|
|
class NotFoundError(BusinessError):
|
|
def __init__(self, msg: str = "数据不存在") -> None:
|
|
super().__init__(msg, code=404)
|
|
|
|
|
|
class ConflictError(BusinessError):
|
|
"""唯一键冲突 / 状态冲突。"""
|
|
|
|
def __init__(self, msg: str = "数据冲突") -> None:
|
|
super().__init__(msg, code=409)
|
|
|
|
|
|
class AuthError(BusinessError):
|
|
def __init__(self, msg: str = "未登录或登录已过期") -> None:
|
|
super().__init__(msg, code=401)
|
|
|
|
|
|
class PermissionError_(BusinessError):
|
|
def __init__(self, msg: str = "没有操作权限") -> None:
|
|
super().__init__(msg, code=403)
|
|
|
|
|
|
class RuleError(BusinessError):
|
|
"""高级筛选器规则不合法。"""
|
|
|
|
def __init__(self, msg: str = "筛选规则不合法") -> None:
|
|
super().__init__(msg, code=422)
|
|
|
|
|
|
# 给 FastAPI 的 HTTPException 留个短别名,方便 api 层按需使用
|
|
from fastapi import HTTPException as HTTPException # noqa: E402,F401
|