Skip to main content

ValidationError

Struct ValidationError 

Source
pub struct ValidationError {
    pub error_type: &'static str,
    pub loc: Vec<LocItem>,
    pub msg: String,
    pub input: Option<Value>,
    pub ctx: Option<HashMap<String, Value>>,
}
Expand description

A single validation error item.

This structure matches FastAPI/Pydantic v2’s validation error format exactly, allowing for seamless compatibility with clients expecting FastAPI responses.

§Examples

use fastapi_core::error::{ValidationError, loc, error_types};
use serde_json::json;

// Missing required field
let error = ValidationError::missing(loc::query("q"));
assert_eq!(error.error_type, "missing");

// String too short with context
let error = ValidationError::new(error_types::STRING_TOO_SHORT, loc::body_field("name"))
    .with_msg("String should have at least 3 characters")
    .with_input(json!("ab"))
    .with_ctx_value("min_length", json!(3));

Fields§

§error_type: &'static str

Error type identifier (e.g., “missing”, “string_too_short”).

§loc: Vec<LocItem>

Location path as a tuple of strings and integers.

Examples:

  • ["query", "q"] for query parameter
  • ["body", "user", "email"] for nested body field
  • ["body", "items", 0, "name"] for array item
§msg: String

Human-readable error message.

§input: Option<Value>

The input value that failed validation.

This is the actual value the user provided that caused the error.

§ctx: Option<HashMap<String, Value>>

Additional context about the validation constraint.

Examples:

  • {"min_length": 3} for string_too_short
  • {"ge": 0} for greater_than_equal
  • {"pattern": "^\\d+$"} for pattern mismatch

Implementations§

Source§

impl ValidationError

Source

pub fn new(error_type: &'static str, loc: Vec<LocItem>) -> Self

Create a new validation error.

Source

pub fn missing(loc: Vec<LocItem>) -> Self

Create a “missing” error for a required field.

Source

pub fn string_too_short(loc: Vec<LocItem>, min_length: usize) -> Self

Create a “string_too_short” error.

Source

pub fn string_too_long(loc: Vec<LocItem>, max_length: usize) -> Self

Create a “string_too_long” error.

Source

pub fn type_error(loc: Vec<LocItem>, expected_type: &'static str) -> Self

Create a type error (e.g., expected int, got string).

Source

pub fn json_invalid(loc: Vec<LocItem>, message: impl Into<String>) -> Self

Create a JSON parsing error.

Source

pub fn with_msg(self, msg: impl Into<String>) -> Self

Set the human-readable message.

Source

pub fn with_input(self, input: Value) -> Self

Set the input value.

Source

pub fn with_ctx_value(self, key: impl Into<String>, value: Value) -> Self

Add a context key-value pair.

Source

pub fn with_ctx(self, ctx: HashMap<String, Value>) -> Self

Set the full context map.

Source

pub fn with_loc_prefix(self, prefix: Vec<LocItem>) -> Self

Add location items to the path.

Source

pub fn with_loc_suffix(self, item: impl Into<LocItem>) -> Self

Append a location item to the path.

Trait Implementations§

Source§

impl Clone for ValidationError

Source§

fn clone(&self) -> ValidationError

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ValidationError

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Extend<ValidationError> for ValidationErrors

Source§

fn extend<T: IntoIterator<Item = ValidationError>>(&mut self, iter: T)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl FromIterator<ValidationError> for ValidationErrors

Source§

fn from_iter<T: IntoIterator<Item = ValidationError>>(iter: T) -> Self

Creates a value from an iterator. Read more
Source§

impl Serialize for ValidationError

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ResponseModel for T
where T: Serialize,

Source§

fn validate(&self) -> Result<(), ResponseValidationError>

Validate the response model before serialization. Read more
Source§

fn model_name() -> &'static str

Get the model name for error messages.
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ResponseProduces<T> for T