[Python] Remove exeption type in pydantic field validator error message

Discussão em 'Python' iniciado por Stack, Maio 27, 2025.

  1. Stack

    Stack Membro Participativo

    I am using fastapi with pydantic for a school project. Let's say I have this little code:

    from pydantic import BaseModel, Field, model_validator

    class Product(BaseModel):
    price: float = Field(ge=0, description="Price must be non-negative")

    @model_validator(mode="before")
    def validate_price(cls, values):
    if values.get("price") < 0:
    raise ValueError("Price cannot be negative")
    return values

    try:
    product = Product(price=-100)
    except Exception as e:
    print(e)


    The console log the message:

    1 validation error for Product
    Value error, Price cannot be negative [type=value_error, input_value={'price': -100}, input_type=dict]
    For further information visit https://errors.pydantic.dev/2.11/v/value_error


    My question is, how to remove the text Value error, in the full string Value error, Price cannot be negative with a nice and clean way?

    The only workaround I found is the next one, the exeption handler from fastapi. I provide my full handler, you just need to look for lines who define error_type and error_message:

    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request, exc):
    errors_dict = {}
    for error in exc.errors():
    error_type = error.get("type").capitalize().replace("_", " ")
    error_message = error.get("msg").removeprefix(f"{error_type}, ")
    location = error.get("loc")[-1]
    errors_dict[location] = {"type": error.get("type"), "message": error_message}
    return JSONResponse(
    status_code=400,
    content={"message": "Erreur lors de la validation", "errors": error_dict},
    )


    I am expecting to alter the message at the pydantic level, the lowest rather than at the fast api level.

    Thanks for advance :)

    Continue reading...

Compartilhe esta Página