ValidationError

Struct ValidationError 

Source
pub struct ValidationError {
    pub violations: SmallVec<[Violation; 4]>,
}
Expand description

Represents a collection of validation violations.

This type aggregates all validation errors that occur during validation of a domain object. It supports merging errors from multiple fields and nested structures.

§Examples

use domainstack::{ValidationError, Path};

let mut err = ValidationError::new();
err.push("email", "invalid_email", "Invalid email format");
err.push("age", "out_of_range", "Must be between 18 and 120");

assert_eq!(err.violations.len(), 2);
assert!(!err.is_empty());

§Nested Errors

use domainstack::{ValidationError, Path};

let mut child_err = ValidationError::new();
child_err.push("value", "invalid_email", "Invalid email format");

let mut parent_err = ValidationError::new();
parent_err.merge_prefixed("email", child_err);

// Error path becomes "email.value"
assert_eq!(parent_err.violations[0].path.to_string(), "email.value");

Fields§

§violations: SmallVec<[Violation; 4]>

Implementations§

Source§

impl ValidationError

Source

pub fn new() -> Self

Source

pub fn is_empty(&self) -> bool

Source

pub fn single( path: impl Into<Path>, code: &'static str, message: impl Into<String>, ) -> Self

Source

pub fn push( &mut self, path: impl Into<Path>, code: &'static str, message: impl Into<String>, )

Source

pub fn extend(&mut self, other: ValidationError)

Source

pub fn merge_prefixed( &mut self, prefix: impl Into<Path>, other: ValidationError, )

Merges violations from another error with a path prefix.

This is optimized to avoid cloning the prefix for each violation. The prefix segments are collected once and reused for all violations.

§Performance
  • Old: O(n) prefix clones where n = number of violations
  • New: O(1) prefix collection + O(n * m) segment clones where m = avg segments per path

For typical use cases (< 10 violations), this optimization reduces allocations significantly.

Source

pub fn field_errors_map(&self) -> BTreeMap<String, Vec<String>>

👎Deprecated since 0.5.0: Use field_violations_map() instead to preserve error codes and metadata. This method only returns messages and loses important error information.

Returns a map of field paths to error messages.

⚠️ Warning: This method only returns messages and loses error codes and metadata. For complete error information including codes (needed for proper error classification, client-side handling, and internationalization), use field_violations_map() instead.

§Examples
use domainstack::ValidationError;

let mut err = ValidationError::new();
err.push("email", "invalid_format", "Invalid email format");
err.push("email", "too_long", "Email too long");

let map = err.field_errors_map();
assert_eq!(map.get("email").unwrap().len(), 2);
// Note: Error codes "invalid_format" and "too_long" are lost!
Source

pub fn field_violations_map(&self) -> BTreeMap<String, Vec<&Violation>>

Source

pub fn prefixed(self, prefix: impl Into<Path>) -> Self

Returns a new ValidationError with all paths prefixed.

§Performance

This method is optimized to collect prefix segments once and reuse them, avoiding repeated cloning of the prefix path.

Source

pub fn map_messages<F>(self, f: F) -> Self
where F: Fn(String) -> String,

Transform all violation messages using the provided function.

This is useful for internationalization (i18n), message formatting, or any other message transformation needs.

§Examples
use domainstack::ValidationError;

let mut err = ValidationError::new();
err.push("email", "invalid", "Invalid email");
err.push("age", "too_young", "Must be 18+");

// Add prefix to all messages
let err = err.map_messages(|msg| format!("Error: {}", msg));

assert_eq!(err.violations[0].message, "Error: Invalid email");
assert_eq!(err.violations[1].message, "Error: Must be 18+");
§Internationalization Example
use domainstack::ValidationError;

let mut err = ValidationError::new();
err.push("email", "invalid_email", "Invalid email format");

// Translate messages based on error code
let err = err.map_messages(|msg| {
    // In a real app, this would use error codes for translation
    "Formato de email inválido".to_string()
});

assert_eq!(err.violations[0].message, "Formato de email inválido");
Source

pub fn filter<F>(self, f: F) -> Self
where F: Fn(&Violation) -> bool,

Filter violations based on a predicate.

This is useful for removing certain types of errors based on custom criteria.

§Examples
use domainstack::ValidationError;

let mut err = ValidationError::new();
err.push("email", "warning", "Email format questionable");
err.push("age", "invalid", "Age is required");
err.push("name", "warning", "Name seems unusual");

// Remove all warnings, keep only errors
let err = err.filter(|v| v.code != "warning");

assert_eq!(err.violations.len(), 1);
assert_eq!(err.violations[0].code, "invalid");

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 Default for ValidationError

Source§

fn default() -> ValidationError

Returns the “default value” for a type. Read more
Source§

impl Display for ValidationError

Source§

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

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

impl Error for ValidationError

1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0: use the Display impl or to_string()
1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0: replaced by Error::source, which can support downcasting
Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl PartialEq for ValidationError

Source§

fn eq(&self, other: &ValidationError) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for ValidationError

Source§

impl StructuralPartialEq for ValidationError

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, 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> 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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.