Files
meijiaka-zy/python-api/app/core/exceptions.py
T

90 lines
2.1 KiB
Python

"""
自定义异常类
============
"""
from fastapi import HTTPException, status
class AppException(HTTPException):
"""应用基础异常"""
def __init__(
self,
status_code: int,
message: str = "操作失败",
detail: dict | None = None,
):
super().__init__(status_code=status_code, detail=detail or {})
self.message = message
class NotFoundException(AppException):
"""资源不存在"""
def __init__(self, message: str = "资源不存在"):
super().__init__(
status_code=status.HTTP_404_NOT_FOUND,
message=message,
)
class ValidationException(AppException):
"""参数验证失败"""
def __init__(self, message: str = "参数验证失败"):
super().__init__(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
message=message,
)
class UnauthorizedException(AppException):
"""未授权"""
def __init__(self, message: str = "未授权,请先登录"):
super().__init__(
status_code=status.HTTP_401_UNAUTHORIZED,
message=message,
)
class ForbiddenException(AppException):
"""禁止访问"""
def __init__(self, message: str = "无权访问该资源"):
super().__init__(
status_code=status.HTTP_403_FORBIDDEN,
message=message,
)
class BusinessException(AppException):
"""业务逻辑错误"""
def __init__(self, message: str = "业务操作失败"):
super().__init__(
status_code=status.HTTP_400_BAD_REQUEST,
message=message,
)
class ModelUnavailableException(AppException):
"""AI 模型不可用"""
def __init__(self, message: str = "AI 模型服务暂时不可用"):
super().__init__(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
message=message,
)
class TaskFailedException(AppException):
"""异步任务执行失败"""
def __init__(self, message: str = "任务执行失败"):
super().__init__(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
message=message,
)