97 lines
2.7 KiB
Python
97 lines
2.7 KiB
Python
"""
|
|
自定义异常模块
|
|
|
|
定义应用级别的异常类,用于统一错误处理。
|
|
"""
|
|
from typing import Any, Optional
|
|
|
|
|
|
class AppException(Exception):
|
|
"""应用基础异常类"""
|
|
|
|
def __init__(
|
|
self,
|
|
code: int = 500,
|
|
message: str = "服务器内部错误",
|
|
data: Any = None
|
|
):
|
|
self.code = code
|
|
self.message = message
|
|
self.data = data
|
|
super().__init__(self.message)
|
|
|
|
|
|
class BadRequestError(AppException):
|
|
"""请求参数错误 (400)"""
|
|
|
|
def __init__(self, message: str = "请求参数错误", data: Any = None):
|
|
super().__init__(code=400, message=message, data=data)
|
|
|
|
|
|
class UnauthorizedError(AppException):
|
|
"""未授权错误 (401)"""
|
|
|
|
def __init__(self, message: str = "未授权,请先登录", data: Any = None):
|
|
super().__init__(code=401, message=message, data=data)
|
|
|
|
|
|
class ForbiddenError(AppException):
|
|
"""禁止访问错误 (403)"""
|
|
|
|
def __init__(self, message: str = "无权限访问", data: Any = None):
|
|
super().__init__(code=403, message=message, data=data)
|
|
|
|
|
|
class NotFoundError(AppException):
|
|
"""资源不存在错误 (404)"""
|
|
|
|
def __init__(self, resource: str = "资源", data: Any = None):
|
|
super().__init__(code=404, message=f"{resource}不存在", data=data)
|
|
|
|
|
|
class ConflictError(AppException):
|
|
"""资源冲突错误 (409)"""
|
|
|
|
def __init__(self, message: str = "资源已存在", data: Any = None):
|
|
super().__init__(code=409, message=message, data=data)
|
|
|
|
|
|
class ValidationError(AppException):
|
|
"""数据验证错误 (422)"""
|
|
|
|
def __init__(self, message: str = "数据验证失败", data: Any = None):
|
|
super().__init__(code=422, message=message, data=data)
|
|
|
|
|
|
class InternalError(AppException):
|
|
"""服务器内部错误 (500)"""
|
|
|
|
def __init__(self, message: str = "服务器内部错误", data: Any = None):
|
|
super().__init__(code=500, message=message, data=data)
|
|
|
|
|
|
class ServiceUnavailableError(AppException):
|
|
"""服务不可用错误 (503)"""
|
|
|
|
def __init__(self, message: str = "服务暂时不可用", data: Any = None):
|
|
super().__init__(code=503, message=message, data=data)
|
|
|
|
|
|
class ModerationError(Exception):
|
|
"""内容审核服务异常
|
|
|
|
当内容审核服务调用失败时抛出此异常。
|
|
"""
|
|
|
|
def __init__(self, message: str, original_error: Optional[Exception] = None):
|
|
"""
|
|
初始化审核异常
|
|
|
|
Args:
|
|
message: 错误消息
|
|
original_error: 原始异常对象(可选)
|
|
"""
|
|
self.message = message
|
|
self.original_error = original_error
|
|
super().__init__(self.message)
|