You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.4 KiB
43 lines
1.4 KiB
from functools import wraps
|
|
from fastapi import HTTPException
|
|
from app.core.logger import logger
|
|
|
|
class ErrorHandler:
|
|
"""错误处理中间件"""
|
|
|
|
@staticmethod
|
|
def handle_error(f):
|
|
@wraps(f)
|
|
async def decorated_function(*args, **kwargs):
|
|
try:
|
|
return await f(*args, **kwargs)
|
|
except HTTPException as e:
|
|
logger.error(f"HTTP错误: {str(e)}")
|
|
raise e
|
|
except Exception as e:
|
|
logger.error(f"处理请求时发生错误: {str(e)}", exc_info=True)
|
|
raise HTTPException(
|
|
status_code=500,
|
|
detail={
|
|
"error": str(e),
|
|
"message": "服务器内部错误"
|
|
}
|
|
)
|
|
return decorated_function
|
|
|
|
@staticmethod
|
|
def handle_validation_error(f):
|
|
@wraps(f)
|
|
async def decorated_function(*args, **kwargs):
|
|
try:
|
|
return await f(*args, **kwargs)
|
|
except ValueError as e:
|
|
logger.error(f"请求参数验证失败: {str(e)}")
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail={
|
|
"error": str(e),
|
|
"message": "请求参数无效"
|
|
}
|
|
)
|
|
return decorated_function
|