Handling Python Pydantic Validation Errors
Learn how to catch, inspect, and customize Pydantic validation errors in Python, including error structure, manual raising, and FastAPI request handling.

Consider a Pydantic model that expects a string and an integer:
from pydantic import BaseModel
class User(BaseModel):
name: str
age: intPassing invalid data raises a ValidationError:
from pydantic import ValidationError
try:
User(name="Alice", age="twenty")
except ValidationError as e:
print(e)The printed error shows the field, the invalid value, and the reason. ValidationError is the exception Pydantic raises when data does not match the model. This article explains its structure, how to handle it in code, and how to customize the messages it produces. The examples use the Pydantic v2 API.
Understanding the ValidationError Structure
A ValidationError instance exposes two useful methods: .errors() and .json(). The .errors() method returns a list of dictionaries, each describing a single validation problem. The .json() method returns the same details as a JSON string. In Pydantic v2, common error keys include:
loc: a tuple of path segments, e.g.,('age',)for a field error.msg: a human-readable message, e.g., "Input should be a valid integer".type: a machine-readable error type, e.g.,int_parsing.input: the invalid value that was passed.
Depending on the Pydantic version and options, the error may also include a url key pointing to the error documentation. For example, the error from the earlier code has errors() returning something like:
[{'loc': ('age',), 'msg': 'Input should be a valid integer, unable to parse string as an integer', 'type': 'int_parsing', 'input': 'twenty'}]The loc tuple can be nested for models inside models. Accessing these fields programmatically lets you build custom error responses or log structured data.
Catching Validation Errors in Application Code
The most common way to handle a ValidationError is with a try/except block. Because the exception contains all validation problems, you can iterate over .errors() and decide how to react. For example, you might collect all error messages and return them to the caller:
from pydantic import ValidationError
def create_user(data: dict):
try:
user = User(**data)
except ValidationError as e:
messages = [f"{'.'.join(str(x) for x in err['loc'])}: {err['msg']}" for err in e.errors()]
raise ValueError("; ".join(messages)) from e
return userThe from e keeps the original exception as the cause, which is useful for debugging. In a web framework, you might convert the validation error to a 400 or 422 response instead of raising a new exception.
Customizing Validation Error Messages
Pydantic lets you control the message that appears in the msg field. The simplest approach is to use a field validator that raises a ValueError with your own text. For example, to enforce a minimum age:
from pydantic import BaseModel, field_validator
class User(BaseModel):
name: str
age: int
@field_validator('age')
@classmethod
def check_age(cls, v):
if v < 18:
raise ValueError('User must be at least 18 years old')
return vNow passing age=16 produces a value_error. In Pydantic v2, the default message is "Value error, User must be at least 18 years old". You can also use model_validator for cross-field checks. Custom messages are essential when the default messages are too generic for your domain.
Raising Validation Errors Manually
Sometimes you need to raise a ValidationError yourself, for example when re-validating data from an external source. Pydantic v2 provides ValidationError.from_exception_data() for this purpose. It takes a model name and a list of error dicts:
from pydantic import ValidationError
errors = [
{
'loc': ('name',),
'msg': 'Name is required',
'type': 'value_error',
'input': None,
}
]
raise ValidationError.from_exception_data('User', errors)The class method builds a ValidationError that downstream handlers can process uniformly.
Validation Errors in FastAPI and Request Handling
FastAPI uses Pydantic models for request bodies and query parameters. When validation fails, FastAPI returns a 422 Unprocessable Entity response by default. The response body contains a detail list; each item has loc, msg, and type, and may include input or a documentation URL depending on the versions involved. You can customize this behavior with an exception handler for RequestValidationError:
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
app = FastAPI()
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content={"errors": exc.errors()},
)This gives you full control over the response format. In current FastAPI versions, RequestValidationError is a separate exception class rather than a subclass of Pydantic's ValidationError, but it exposes a similar .errors() method, so you can handle the error structure in the same style.
Debugging and Operational Considerations
In production, validation errors should be logged with enough context to diagnose the problem. The input field in each error dict contains the offending value, which is useful for debugging but may contain sensitive data. Consider redacting or truncating input before logging. Also, Pydantic's validation is CPU-bound; for high-throughput services, the overhead of repeated validation can be significant. If you validate the same data multiple times, cache the validated result when possible. Finally, keep your Pydantic version up to date, because error structures and messages can change between minor releases, which can affect code that parses errors() output.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.