Handle invalid model data
A model receives malformed or incorrectly typed input.
Pydantic · Class
ValidationError is raised when Pydantic rejects input during validation. Catch it to access a readable report describing the model, location, expected value, error type, and received input.
ValidationError is raised when Pydantic cannot validate input against a model or other declared schema. Catch it to inspect human-readable output or structured details such as the failing location, message, error type, and supplied input.
class ValidationError(Exception)Raises ValidationError when validation fails; the documented example shows the exception being caught and printed.
from pydantic import BaseModel, ValidationError
class User(BaseModel):
age: int
try:
User(age="not an integer")
except ValidationError as exc:
print(exc.errors())
Catch the exception and inspect structured error details.
A model receives malformed or incorrectly typed input.
An application needs field-level diagnostics for a response.
Debugging reveals unexpected values entering a model.
ValidationError reports that input failed Pydantic validation. It can be caught and printed or inspected programmatically; the documentation example shows its string form identifying the model, field, message, error type, and input details.
Follow-up: How would you handle several invalid fields? Inspect the structured error collection rather than parsing the formatted string, then map each location to an appropriate application response.
It is raised when a configured validation rule rejects input, such as forbidding an extra field. The resulting diagnostic identifies where validation failed and why.
Follow-up: What should an API return? Convert the structured diagnostics into your API's error format while avoiding exposure of sensitive input values.
The displayed diagnostic includes the field location, a validation message, an error type, and information about the received input. This makes the exception useful both for debugging and for building field-level error responses.
Follow-up: Why prefer structured diagnostics? They remain machine-readable when wording changes and can be grouped by location or error type.
BaseModelConfigDictmodel_validate