Skip to content

Instantly share code, notes, and snippets.

@ixuuux
Last active May 17, 2023 05:35
Show Gist options
  • Save ixuuux/0296f32f4749c4c24becdce2e0f0e49d to your computer and use it in GitHub Desktop.
Save ixuuux/0296f32f4749c4c24becdce2e0f0e49d to your computer and use it in GitHub Desktop.
将fastapi(其实是pydantic)参数验证错误的信息“翻译”
import re
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError
app = FastAPI()
# ------------------ 错误捕捉处理 ------------------
@app.exception_handler(RequestValidationError)
async def request_validation_error(request: Request, exc: RequestValidationError):
# 处理参数验证失败
exc = str(exc).replace('\n ', '').replace('\n', ' ')
exc = exc.replace('validation errors for Request', '个参数验证错误;')
exc = exc.replace('validation error for Request', '个参数验证错误;')
exc = exc.replace('value is not a valid', '字段的值不是有效的')
exc = exc.replace('field required', '字段为必填项')
exc = re.sub('\(type=.*?\)', ';', exc)
exc = exc.replace(' ;', ';')
return JSONResponse(
status_code=200,
content={'code': 422, 'msg': f'参数有误[{exc}]', 'data': None}
)
# 输出结果示例:{"code":422,"msg":"参数有误[3 个参数验证错误; query -> uid 字段的值不是有效的 integer; query -> page 字段的值不是有效的 integer; query -> pageSize 字段的值不是有效的 integer;]","data":null}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment