You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI中如何自定义验证错误提示信息?

FastAPI 自定义验证错误提示信息

FastAPI本身没有直接的error_message参数,但可以通过以下两种方式实现自定义验证错误提示:

方法一:通过Query的validation_kwargs指定自定义消息

利用Pydantic的验证参数传递机制,直接在Query中配置validation_kwargs来覆盖默认错误消息:

import uvicorn
from fastapi import FastAPI, Query
from typing import Annotated

app = FastAPI()

@app.get("/")
async def read_items(
    # 自定义max_length验证错误消息
    name: str = Query(
        max_length=5,
        validation_kwargs={"max_length": "name too long"}
    ),
    # 自定义整数类型转换错误消息
    age: Annotated[int, Query(validation_kwargs={"type": "age need integer"})] = Query(...)
):
    return '...'

if __name__ == '__main__':
    uvicorn.run(app="main:app", host="localhost", port=5000)

说明:

  • 针对max_length这类具体验证规则,validation_kwargs的键名要和规则名一致(比如max_length),值为自定义提示。
  • 类型转换错误(如字符串转整数失败),通过validation_kwargs中的type键指定自定义消息。

方法二:全局异常处理器统一修改错误信息

如果需要批量处理多个字段或错误类型,可自定义全局异常处理器捕获RequestValidationError,逐个修改错误内容:

import uvicorn
from fastapi import FastAPI, Query, Request
from fastapi.responses import JSONResponse
from fastapi.exceptions import RequestValidationError

app = FastAPI()

@app.exception_handler(RequestValidationError)
async def custom_validation_handler(request: Request, exc: RequestValidationError):
    modified_errors = []
    for err in exc.errors():
        # 根据错误类型和字段定位替换消息
        if err["type"] == "value_error.any_str.max_length" and err["loc"][1] == "name":
            err["msg"] = "name too long"
        elif err["type"] == "type_error.integer" and err["loc"][1] == "age":
            err["msg"] = "age need integer"
        modified_errors.append(err)
    return JSONResponse(
        status_code=422,
        content={"detail": modified_errors}
    )

@app.get("/")
async def read_items(
    name: str = Query(max_length=5),
    age: int = Query(...)
):
    return '...'

if __name__ == '__main__':
    uvicorn.run(app="main:app", host="localhost", port=5000)

说明:

  • 该方法会捕获所有请求验证错误,通过错误的type(错误类型)和loc(字段位置)精准匹配,替换对应的提示文本。
  • 适合需要统一管理大量自定义错误消息的场景,灵活性更强。

测试上述任意一种方案后,请求http://localhost:5000/?name=asdfasdfasdfasdreerer&age=s,即可得到你期望的自定义错误响应。

内容的提问来源于stack exchange,提问作者zhizunbao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 20:32:38