""" 自定义异常类 """ from typing import Optional, Any, Dict from fastapi import HTTPException, status class BaseAPIException(HTTPException): """基础 API 异常类""" def __init__( self, status_code: int, message: str, error_code: Optional[str] = None, error_detail: Optional[Any] = None, headers: Optional[Dict[str, Any]] = None, ): self.message = message self.error_code = error_code or f"ERROR_{status_code}" self.error_detail = error_detail super().__init__( status_code=status_code, detail={ "error_code": self.error_code, "message": self.message, "error_detail": self.error_detail, }, headers=headers, ) class FileUploadException(BaseAPIException): """文件上传异常""" def __init__(self, message: str, error_detail: Optional[Any] = None): super().__init__( status_code=status.HTTP_400_BAD_REQUEST, message=message, error_code="FILE_UPLOAD_ERROR", error_detail=error_detail, ) class FileParseException(BaseAPIException): """文件解析异常""" def __init__(self, message: str, error_detail: Optional[Any] = None): super().__init__( status_code=status.HTTP_400_BAD_REQUEST, message=message, error_code="FILE_PARSE_ERROR", error_detail=error_detail, ) class LLMAPIException(BaseAPIException): """大模型 API 调用异常""" def __init__(self, message: str, error_detail: Optional[Any] = None, retryable: bool = False): super().__init__( status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, message=message, error_code="LLM_API_ERROR", error_detail=error_detail, ) self.retryable = retryable class ValidationException(BaseAPIException): """数据验证异常""" def __init__(self, message: str, error_detail: Optional[Any] = None): super().__init__( status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, message=message, error_code="VALIDATION_ERROR", error_detail=error_detail, ) class NotFoundException(BaseAPIException): """资源不存在异常""" def __init__(self, resource: str, identifier: Optional[str] = None): message = f"{resource} not found" if identifier: message += f": {identifier}" super().__init__( status_code=status.HTTP_404_NOT_FOUND, message=message, error_code="NOT_FOUND", error_detail={"resource": resource, "identifier": identifier}, )