Files
aiagent/backend/app/core/exceptions.py
2026-01-19 00:09:36 +08:00

87 lines
2.4 KiB
Python

"""
自定义异常类
"""
from fastapi import HTTPException, status
class BaseAPIException(HTTPException):
"""基础API异常"""
def __init__(self, status_code: int, detail: str, error_code: str = None):
super().__init__(status_code=status_code, detail=detail)
self.error_code = error_code
class ValidationError(BaseAPIException):
"""验证错误"""
def __init__(self, detail: str):
super().__init__(
status_code=status.HTTP_400_BAD_REQUEST,
detail=detail,
error_code="VALIDATION_ERROR"
)
class NotFoundError(BaseAPIException):
"""资源未找到错误"""
def __init__(self, resource: str, resource_id: str = None):
detail = f"{resource}不存在"
if resource_id:
detail += f": {resource_id}"
super().__init__(
status_code=status.HTTP_404_NOT_FOUND,
detail=detail,
error_code="NOT_FOUND"
)
class UnauthorizedError(BaseAPIException):
"""未授权错误"""
def __init__(self, detail: str = "未授权访问"):
super().__init__(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=detail,
error_code="UNAUTHORIZED"
)
class ForbiddenError(BaseAPIException):
"""禁止访问错误"""
def __init__(self, detail: str = "无权访问此资源"):
super().__init__(
status_code=status.HTTP_403_FORBIDDEN,
detail=detail,
error_code="FORBIDDEN"
)
class ConflictError(BaseAPIException):
"""资源冲突错误"""
def __init__(self, detail: str):
super().__init__(
status_code=status.HTTP_409_CONFLICT,
detail=detail,
error_code="CONFLICT"
)
class InternalServerError(BaseAPIException):
"""内部服务器错误"""
def __init__(self, detail: str = "服务器内部错误"):
super().__init__(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=detail,
error_code="INTERNAL_ERROR"
)
class WorkflowExecutionError(BaseAPIException):
"""工作流执行错误"""
def __init__(self, detail: str, node_id: str = None):
if node_id:
detail = f"节点 {node_id} 执行失败: {detail}"
super().__init__(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=detail,
error_code="WORKFLOW_EXECUTION_ERROR"
)