Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 38 ยท Validation and Constraints

Validation Errors in Detail

Read and handle Pydantic ValidationError: the errors() structure, loc paths, error types, error_count, JSON output, custom messages and turning errors into friendly text.

When data is wrong, Pydantic raises a ValidationError. It is not a plain message string: it carries a structured list of problems that your code can inspect, translate, log, or send back to an API client. Handling it well is what separates a friendly application from one that prints a stack trace.

Catching the error

ValidationError is a subclass of ValueError, so except ValueError also catches it, but it is clearer to import and catch ValidationError itself.

Python Printing a ValidationError

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The printed form is meant for developers: field name, a message, the type, the offending input and a link to the docs. For programs, use the structured forms.

errors(): the list of problems

e.errors() returns a list of dictionaries. Each has these keys:

Key Meaning
type a stable machine-readable code such as missing, int_parsing, greater_than_equal
loc a tuple path to the field, for example ('lines', 1, 'price')
msg a human-readable English message
input the value that was rejected
ctx extra data such as the limit ({'ge': 18})
url link to documentation about this error type
Python The structure of errors()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Use type (not msg) for decisions in code: the wording of messages may change between versions, but the type codes are stable.

Turning errors into a friendly response

A common need is a dictionary of field -> message for a form or an API response:

Python Friendly error messages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same approach translates messages into another language: look up the type in a table for each language and fill in values from ctx.

JSON output

e.json() gives the errors as a JSON string, ready for a response body, and e.errors() can be made JSON-safe with include_context=False or by converting values. FastAPI uses exactly this structure for its 422 responses.

Python Errors as JSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Validating JSON text

When you use model_validate_json, the error type for bad JSON syntax is json_invalid, and for wrong values inside valid JSON the loc points into the JSON structure:

Python JSON syntax errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Custom error messages

You cannot edit the messages inside the Rust core, but you can replace them in your own code: catch the error and map types to text as above. Inside your own custom validators (a later chapter) you raise a ValueError with the message you want, and Pydantic wraps it as an error of type value_error.

Python A ValueError becomes a value_error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice that the message is prefixed with Value error, .... That prefix identifies messages that came from your own validators.

A ValidationError is not for bugs

Reserve ValidationError for bad input: it means "the caller sent wrong data", and you should respond with a clear message (HTTP 400 or 422 in an API). A ValidationError that appears while building a model from data you generated yourself is usually a programming bug, and you should let it propagate and fix the code.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which key of an error dictionary should your code use to decide how to react, rather than the message text?

    type is a stable machine-readable code. Messages may be reworded between versions.
  2. 2. What does loc ('lines', 1, 'price') mean?

    loc is a path through keys and list indexes down to the failing value.
  3. 3. Which method returns the number of problems in a ValidationError?

    error_count() returns the number of errors; errors() returns the list itself.
  4. 4. What error type does model_validate_json produce for '{"x": 1' (missing closing brace)?

    Broken JSON syntax is reported as json_invalid before any field is validated.

Summary

  • ValidationError carries structured errors: type, loc, msg, input, ctx, url.
  • Use e.errors() for code, e.json() for responses, and e.error_count() for the number of problems.
  • Decide on type codes, not on message text; map types to friendly or translated messages.
  • Errors raised as ValueError inside your validators appear as type value_error.
  • Treat ValidationError as "bad input": report it clearly instead of crashing.

Next: Strict Mode and Coercion