constrained_type/
error.rs

1#![deny(missing_docs)]
2
3//! Error types for the crate
4
5use std::fmt;
6
7use thiserror::Error;
8
9/// An alias for results returned by functions of this crate
10pub type ConstrainedTypeResult<T> = ::std::result::Result<T, ConstrainedTypeError>;
11
12/// The concrete error kind
13#[derive(Error, Debug, Eq, PartialEq)]
14pub enum ConstrainedTypeErrorKind {
15    /// Number exceeded the maximum value
16    #[error("{field_name:?} must not be greater than {expected:?}, {found:?}")]
17    InvalidMaxVal {
18        /// Field name shown in the error
19        field_name: String,
20        /// Specified maximum value
21        expected: String,
22        /// Actual value
23        found: String,
24    },
25    /// Number exceeded the minimum value
26    #[error("{field_name:?} must not be less than {expected:?}, {found:?}")]
27    InvalidMinVal {
28        /// Field name shown in the error
29        field_name: String,
30        /// Specified minimum value
31        expected: String,
32        /// Actual value
33        found: String,
34    },
35    /// String does not match the pattern
36    #[error("{field_name:?} does not match pattern {expected:?} for value {found:?}")]
37    InvalidPattern {
38        /// Field name shown in the error
39        field_name: String,
40        /// Specified pattern
41        expected: String,
42        /// Actual value
43        found: String,
44    },
45    /// String is empty
46    #[error("{field_name:?} must not be empty")]
47    InvalidOption {
48        /// Field name shown in the error
49        field_name: String,
50    },
51    /// Character data length exceeded the limit
52    #[error("{field_name:?} must not be greater than {expected:?} characters, {found:?}")]
53    InvalidMaxLen {
54        /// Field name shown in the error
55        field_name: String,
56        /// Specified character limit
57        expected: String,
58        /// Actual value
59        found: String,
60    },
61}
62
63/// The error type for errors that get returned in the crate
64#[derive(Error, Debug, Eq, PartialEq)]
65pub struct ConstrainedTypeError {
66    kind: ConstrainedTypeErrorKind,
67}
68
69impl ConstrainedTypeError {
70    /// Get the kind of the error
71    pub fn kind(&self) -> &ConstrainedTypeErrorKind {
72        &self.kind
73    }
74}
75
76impl From<ConstrainedTypeErrorKind> for ConstrainedTypeError {
77    fn from(kind: ConstrainedTypeErrorKind) -> ConstrainedTypeError {
78        ConstrainedTypeError { kind }
79    }
80}
81
82impl<T> From<ConstrainedTypeError> for Result<T, ConstrainedTypeError> {
83    fn from(e: ConstrainedTypeError) -> Self {
84        Err(e)
85    }
86}
87
88impl fmt::Display for ConstrainedTypeError {
89    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
90        fmt::Display::fmt(&self.kind, f)
91    }
92}