Skip to main content

The ValidationError Object

The ValidationError exception is the primary mechanism for reporting validation failures in pydantic-core. When a SchemaValidator encounters data that does not conform to the defined schema, it raises this exception, providing detailed information about what went wrong and where.

The ValidationError Exception​

The ValidationError class is designed for both human readability and programmatic inspection. It encapsulates one or more individual errors discovered during the validation process.

Accessing Error Details​

You can inspect the errors within a ValidationError using several methods:

  • error_count(): Returns the total number of validation errors.
  • errors(): Returns a list of ErrorDetails dictionaries. This is the most common way to programmatically process errors.
  • json(): Returns a JSON-serialized string representation of the errors, which is useful for API responses.
from pydantic_core import SchemaValidator, core_schema, ValidationError

v = SchemaValidator(core_schema.int_schema())

try:
v.validate_python('not an int')
except ValidationError as exc:
print(exc.error_count())
# Output: 1

print(exc.errors())
# Output: [{'type': 'int_parsing', 'loc': (), 'msg': '...', 'input': 'not an int', 'url': '...'}]

The errors() and json() methods accept several optional arguments to customize the output:

  • include_url: Whether to include the documentation URL for the error type (default: True).
  • include_context: Whether to include the ctx dictionary containing values used to render the message (default: True).
  • include_input: Whether to include the original input value that caused the error (default: True).

Error Representation​

When converted to a string (via str() or repr()), ValidationError provides a formatted summary of all errors, including the location, the error message, and the input value.

# Example string representation from pydantic-core/tests/test_errors.py
# 1 validation error for typed-dict
# foo.bar.0
# Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='x', input_type=str]

Error Structure​

Individual errors are represented by the ErrorDetails TypedDict. This structure ensures consistency across different types of validation failures.

ErrorDetails Fields​

FieldTypeDescription
typestrA stable machine-readable identifier for the error (e.g., int_parsing, greater_than).
loctuple[int | str, ...]The path to the error in the input data. Empty for top-level errors.
msgstrA human-readable error message.
inputAnyThe specific input value that failed validation.
ctxdict[str, Any](Optional) Contextual data used to generate the message (e.g., the gt value for a greater_than error).
urlstr(Optional) A link to the Pydantic documentation for this error type.

Note: While loc is a tuple in the Python ErrorDetails object, it is serialized as a list when using the json() method.

Manual Error Creation​

In some cases, such as custom validation logic or testing, you may need to instantiate a ValidationError manually. This is done using the from_exception_data() class method.

Using from_exception_data​

This method requires a title for the error and a list of InitErrorDetails.

from pydantic_core import ValidationError

# Manually creating a ValidationError
exc = ValidationError.from_exception_data(
'MyModel',
[
{
'type': 'greater_than',
'loc': ('a', 2),
'input': 4,
'ctx': {'gt': 5}
}
]
)

InitErrorDetails​

The InitErrorDetails TypedDict is used to define the errors passed to from_exception_data. It requires:

  • type: Either a string slug or a PydanticCustomError.
  • input: The value that caused the error.
  • loc: (Optional) The location of the error.
  • ctx: (Optional) Context for the error.

If the type refers to a built-in error that requires specific context (like greater_than requiring gt), failing to provide that context in ctx will result in a TypeError.

Error Metadata and Templates​

The pydantic_core package provides utilities to inspect all possible error types and their message templates.

list_all_errors()​

The list_all_errors() function returns a list of ErrorTypeInfo objects. This is useful for generating documentation or building custom error handlers that need to know about all possible failure modes.

from pydantic_core import list_all_errors

for error_info in list_all_errors():
print(f"Type: {error_info['type']}")
print(f"Template: {error_info['message_template_python']}")

ErrorTypeInfo​

The ErrorTypeInfo structure provides:

  • type: The error identifier.
  • message_template_python: The template used for Python-based error messages.
  • example_message_python: An example of a rendered message.
  • message_template_json: (Optional) The template used when the input type is JSON (e.g., using "null" instead of "None").

Configuration​

The inclusion of documentation URLs in ValidationError outputs can be controlled globally via the PYDANTIC_ERRORS_INCLUDE_URL environment variable.

  • Enable: Set to 1, true, or yes.
  • Disable: Set to 0, false, or no.

Because pydantic-core caches this configuration for performance, this environment variable must be set before the first ValidationError is created or its representation is accessed within the process.