Skip to main content

Error Handling

Error handling in this codebase is divided into two distinct categories: Validation Errors, which occur when data fails to meet schema requirements, and User Errors, which occur when the library is used incorrectly (e.g., invalid model configuration).

Validation Errors

The ValidationError class, defined in pydantic_core, is the primary exception raised when validation fails. It is a subclass of ValueError and contains a collection of one or more errors encountered during the validation process.

Inspecting Errors

When a ValidationError is caught, you can inspect the specific failures using the .errors() or .json() methods.

from pydantic import BaseModel, ValidationError

class User(BaseModel):
id: int
name: str

try:
User(id='not-an-int', name='John')
except ValidationError as exc:
# Returns a list of ErrorDetails dictionaries
print(exc.errors())

# Returns a JSON string representation of the errors
print(exc.json(indent=2))

The errors() method accepts several boolean flags to control the output:

  • include_url: Includes a link to the Pydantic documentation for that error type.
  • include_context: Includes the context dictionary (if any) for the error.
  • include_input: Includes the original input value that caused the failure.

Error Structure

Each individual error is represented by the ErrorDetails TypedDict (found in pydantic_core/__init__.py), which contains the following fields:

FieldTypeDescription
typestrA stable machine-readable identifier for the error (e.g., int_parsing).
loctuple[int | str, ...]The path to the failing field (e.g., ('address', 'street')).
msgstrA human-readable error message.
inputAnyThe actual value that failed validation.
ctxdict[str, Any](Optional) Contextual data used to render the message.
urlstr(Optional) A URL to documentation for the error.

Customizing Validation Errors

You can raise custom errors within functional validators using PydanticCustomError or PydanticKnownError. These classes allow you to provide specific messages and context that will be included in the final ValidationError.

PydanticCustomError

PydanticCustomError allows you to define a completely custom error type and message template. The template can use placeholders that are filled by the context dictionary.

from pydantic_core import PydanticCustomError
from pydantic import BaseModel, field_validator

class Product(BaseModel):
price: float

@field_validator('price')
@classmethod
def check_price(cls, v: float) -> float:
if v < 0:
raise PydanticCustomError(
'negative_price',
'Price {price} cannot be negative',
{'price': v}
)
return v

PydanticKnownError

PydanticKnownError is used when you want to raise one of Pydantic's built-in error types but provide your own context. This ensures the error type remains consistent with standard Pydantic errors while allowing for custom data.

from pydantic_core import PydanticKnownError

def validate_gt_ten(v: int) -> int:
if v <= 10:
# 'greater_than' is a built-in Pydantic error type
raise PydanticKnownError('greater_than', {'gt': 10})
return v

Programmatic Error Creation

In some cases, such as when wrapping external validation logic, you may need to construct a ValidationError manually. This is done using the from_exception_data class method and the InitErrorDetails TypedDict.

from pydantic_core import ValidationError, InitErrorDetails

errors = [
InitErrorDetails(
type='value_error',
loc=('field_name',),
input='invalid_input',
msg='Custom manual error message'
)
]

raise ValidationError.from_exception_data(
title='ManualValidationError',
line_errors=errors
)

User Errors

PydanticUserError (defined in pydantic/errors.py) is raised when there is a mistake in how Pydantic is being used, rather than a failure in the data being validated. These errors typically occur during model initialization or schema generation.

Common subclasses include:

  • PydanticSchemaGenerationError: Raised when Pydantic cannot generate a CoreSchema for a specific type annotation.
  • PydanticUndefinedAnnotation: Raised when a type hint refers to a name that hasn't been defined yet.
  • PydanticInvalidForJsonSchema: Raised when a model contains types that cannot be represented in JSON Schema.

These errors include a code that links to the Pydantic documentation for troubleshooting.

Configuration

The behavior of error reporting can be influenced by environment variables:

  • PYDANTIC_ERRORS_INCLUDE_URL: Controls whether documentation URLs are included in the repr of a ValidationError. Set to 1 or true to enable (default). Note that this variable can only be set once before the first validation error is generated.