modify: 上报接口 422 问题
This commit is contained in:
@@ -12,6 +12,7 @@ import asyncio
|
|||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
|
|
||||||
from fastapi import FastAPI, Request
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
|
|
||||||
@@ -156,6 +157,35 @@ async def root():
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||||
|
"""
|
||||||
|
请求验证异常处理器,记录详细的验证错误信息和请求体。
|
||||||
|
帮助快速定位 Pydantic 模型与前端/设备上报数据的不匹配问题。
|
||||||
|
"""
|
||||||
|
body = None
|
||||||
|
try:
|
||||||
|
body = await request.body()
|
||||||
|
body_str = body.decode("utf-8")[:2000] if body else "<empty>"
|
||||||
|
except Exception:
|
||||||
|
body_str = "<unable to read body>"
|
||||||
|
|
||||||
|
errors = exc.errors()
|
||||||
|
error_summary = [
|
||||||
|
f"{' -> '.join(str(loc) for loc in e['loc'])}: {e['msg']}"
|
||||||
|
for e in errors
|
||||||
|
]
|
||||||
|
logger.error(
|
||||||
|
f"请求验证失败 [{request.method} {request.url.path}]:\n"
|
||||||
|
f" 错误: {'; '.join(error_summary)}\n"
|
||||||
|
f" 请求体: {body_str}"
|
||||||
|
)
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=422,
|
||||||
|
content={"detail": errors},
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(Exception)
|
@app.exception_handler(Exception)
|
||||||
async def global_exception_handler(_: Request, exc: Exception):
|
async def global_exception_handler(_: Request, exc: Exception):
|
||||||
"""
|
"""
|
||||||
|
|||||||
Reference in New Issue
Block a user