feat: 添加API限流和优化错误处理
Some checks failed
continuous-integration/drone/push Build is failing

- 添加 RateLimitMiddleware 限流中间件 (200请求/分钟)
- 优化 Content-Type 错误返回 400 而非 500
- 添加 JSON 解析错误处理
- 统一 HTTP 异常处理格式
This commit is contained in:
yuliang_guo
2026-01-31 10:50:27 +08:00
parent d59a4355a5
commit 52dccaab79
2 changed files with 137 additions and 3 deletions

View File

@@ -97,6 +97,14 @@ app.add_middleware(
allow_headers=["*"],
)
# 添加限流中间件
from app.core.middleware import RateLimitMiddleware
app.add_middleware(
RateLimitMiddleware,
requests_per_minute=120, # 每分钟最大请求数
burst_limit=200, # 突发请求限制
)
# 健康检查端点
@app.get("/health")
@@ -140,16 +148,60 @@ async def validation_exception_handler(request: Request, exc: RequestValidationE
return JSONResponse(
status_code=422,
content={
"code": 422,
"message": "请求参数验证失败",
"detail": exc.errors(),
"body": exc.body if hasattr(exc, 'body') else None,
},
)
# JSON 解析错误处理
from json import JSONDecodeError
@app.exception_handler(JSONDecodeError)
async def json_decode_exception_handler(request: Request, exc: JSONDecodeError):
"""处理 JSON 解析错误"""
logger.warning(f"JSON解析错误 [{request.method} {request.url.path}]: {exc}")
return JSONResponse(
status_code=400,
content={
"code": 400,
"message": "请求体格式错误,需要有效的 JSON",
"detail": str(exc),
},
)
# HTTP 异常处理
from fastapi import HTTPException
@app.exception_handler(HTTPException)
async def http_exception_handler(request: Request, exc: HTTPException):
"""处理 HTTP 异常"""
return JSONResponse(
status_code=exc.status_code,
content={
"code": exc.status_code,
"message": exc.detail,
},
)
# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
async def global_exception_handler(request: Request, exc: Exception):
"""全局异常处理"""
error_msg = str(exc)
# 检查是否是 Content-Type 相关错误
if "Expecting value" in error_msg or "JSON" in error_msg.upper():
logger.warning(f"请求体解析错误 [{request.method} {request.url.path}]: {error_msg}")
return JSONResponse(
status_code=400,
content={
"code": 400,
"message": "请求体格式错误,请使用 application/json",
},
)
logger.error(f"未处理的异常: {exc}", exc_info=True)
return JSONResponse(
status_code=500,