Field validation exception custom exception information #12325
-
First Check
Commit to Help
Example Codefrom fastapi import FastAPI, Query
@app.get("/items/")
async def read_items(filter_query: str = Query(..., min_length=10, max_length=100, error_msg="Custom exception information ")):
return filter_query
if __name__ == '__main__':
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)DescriptionWhen an exception occurs, custom information is captured through exception middleware and returned . Operating SystemWindows Operating System DetailsNo response FastAPI Versionfastapi version = "0.110.0" Pydantic Versionpydantic 2.7.3 Python Versionpython 3.10.11 Additional ContextNo response |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
|
Hey @YueXiaWyl , In FastAPI, you can't directly pass a custom Here's an example of how you can do it: from fastapi import FastAPI, Query, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
app = FastAPI()
# Custom exception handler
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content={"detail": "Custom exception: Query parameter must be between 10 and 100 characters."},
)
@app.get("/items/")
async def read_items(filter_query: str = Query(..., min_length=10, max_length=100)):
return filter_query
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="127.0.0.1", port=8000)This code will catch any validation error (like when your query parameter is too short or too long) and return a custom error message instead of the default one. So, when a user sends a query that doesn’t meet the validation criteria, they'll get something like: {
"detail": "Custom exception: Query parameter must be between 10 and 100 characters."
}This way, you can make error messages more user-friendly and clear. |
Beta Was this translation helpful? Give feedback.
-
|
You can use from typing import Annotated, Any
from fastapi import FastAPI, Query
from pydantic import ValidationError, ValidatorFunctionWrapHandler, WrapValidator
app = FastAPI()
def override_err(value: Any, handler: ValidatorFunctionWrapHandler) -> str:
try:
return handler(value)
except ValidationError:
raise ValueError("CUSTOM MESSAGE")
@app.get("/items/")
async def read_items(
filter_query: Annotated[
str, Query(min_length=10, max_length=100), WrapValidator(override_err)
],
):
return filter_queryOr, configurable version: from typing import Annotated, Any
from fastapi import FastAPI, Query
from pydantic import ValidationError, ValidatorFunctionWrapHandler, WrapValidator
app = FastAPI()
def wrap_validation_error(msg_prefix: str) -> WrapValidator:
def add_msg(value: Any, handler: ValidatorFunctionWrapHandler) -> str:
try:
return handler(value)
except ValidationError as err:
raise ValueError(f"{msg_prefix}: {err}")
return WrapValidator(add_msg)
@app.get("/items/")
async def read_items(
filter_query: Annotated[
str,
Query(min_length=10, max_length=100),
wrap_validation_error("Custom exception information "),
],
):
return filter_query
|
Beta Was this translation helpful? Give feedback.
You can use
WrapValidatorfor this reason:Or, configurable version: