Read structured validation errors
A validation error can describe several failures at once. Parse its structured errors() result instead of scraping the formatted message. Each entry includes a location, a machine-readable error type and a human message.
Locations are tuples and can include collection indexes, so a nested error can identify exactly which item failed. Error messages and documentation URLs may change between versions. Base program logic on locations and error types, and choose deliberately whether raw rejected input belongs in a log or user response.
from pydantic import BaseModel
from pydantic import ValidationError
class Row(BaseModel):
age: int
try:
Row(age="wrong")
except ValidationError as error:
print([e["loc"] for e in error.errors()])Your task
Implement invalid_fields(raw) validating Profile(name: str, age: int). Return a sorted list of the first location components of all errors, or [] on success. Report both fields when both are absent.
The explanation opens here once every check passes.