Skip to main content

djs_builders/
error.rs

1//! [`ValidationError`]: what `build()` returns when a Discord limit or rule is broken.
2
3use std::{borrow::Cow, fmt};
4
5/// A Discord limit or rule broken by a builder's content, returned by `build()` (D-179).
6///
7/// `build()` stops at the first violation it finds and returns it (D-182). `field` is the
8/// path of the offending value in the JSON sent to Discord, written the way Discord writes it
9/// in its own `50035 Invalid Form Body` errors β€” `title`, `fields[3].name`, `author.url` β€” so
10/// both kinds of error point at the same place.
11///
12/// Texts are measured like Discord measures them: in Unicode code points
13/// ([`str::chars`]), without leading and trailing whitespace (D-183, confirmed on the live
14/// API). An emoji such as πŸ”₯ counts once β€” discord.js would count it twice.
15///
16/// discord.js counterpart: the errors thrown by the setters of `@discordjs/builders`
17/// (`ValidationError` / `CombinedError` from `@sapphire/shapeshift`).
18///
19/// # Examples
20///
21/// ```
22/// use djs_builders::{EmbedBuilder, ValidationError};
23///
24/// let error = EmbedBuilder::new().title("x".repeat(300)).build().unwrap_err();
25/// assert_eq!(
26///     error,
27///     ValidationError::TooLong { field: "title".into(), max: 256, actual: 300 }
28/// );
29/// assert_eq!(error.field(), "title");
30/// assert_eq!(error.to_string(), "title is too long: 300 characters, at most 256 allowed");
31/// ```
32#[derive(Clone, Debug, PartialEq, Eq, Hash)]
33#[non_exhaustive]
34pub enum ValidationError {
35    /// A text is longer than Discord allows.
36    TooLong {
37        /// The path of the text, e.g. `description` or `fields[2].value`.
38        field: Cow<'static, str>,
39        /// The most characters (code points after trimming) Discord allows.
40        max: usize,
41        /// The characters the text has, counted the same way.
42        actual: usize,
43    },
44    /// A list has more items than Discord allows.
45    TooMany {
46        /// The path of the list, e.g. `fields`.
47        field: Cow<'static, str>,
48        /// The most items Discord allows.
49        max: usize,
50        /// The items the list has.
51        actual: usize,
52    },
53    /// A list has fewer items than Discord requires β€” for example an empty action row.
54    TooFew {
55        /// The path of the list, e.g. `components`.
56        field: Cow<'static, str>,
57        /// The fewest items Discord allows.
58        min: usize,
59        /// The items the list has.
60        actual: usize,
61    },
62    /// A value that Discord requires is not set.
63    Missing {
64        /// The path of the value.
65        field: Cow<'static, str>,
66    },
67    /// A number is outside the range Discord allows.
68    OutOfRange {
69        /// The path of the number, e.g. `color`.
70        field: Cow<'static, str>,
71        /// The smallest value allowed.
72        min: i64,
73        /// The largest value allowed.
74        max: i64,
75        /// The value given.
76        actual: i64,
77    },
78    /// A URL does not start with one of the schemes Discord allows for it (D-187, D-190).
79    ///
80    /// Only the scheme is checked; Discord itself rejects a malformed address such as a bare
81    /// `https://`.
82    InvalidUrl {
83        /// The path of the URL, e.g. `author.url`.
84        field: Cow<'static, str>,
85        /// The allowed scheme prefixes, e.g. `["http://", "https://"]` (compared without
86        /// regard to case).
87        allowed: &'static [&'static str],
88    },
89    /// A command, subcommand or option name has a character Discord does not allow (D-194):
90    /// anything but letters, numbers, `-`, `_` and `ΚΌ`, or a letter that has a lower-case
91    /// form.
92    InvalidName {
93        /// The path of the name, e.g. `options[0].name`.
94        field: Cow<'static, str>,
95        /// The first character that is not allowed.
96        character: char,
97    },
98    /// Values that are valid one by one do not work together β€” for example a required option
99    /// after an optional one, or `choices` together with `autocomplete`.
100    Invalid {
101        /// The path of the value that breaks the rule, e.g. `options[1].required`.
102        field: Cow<'static, str>,
103        /// What is wrong, for the error message.
104        reason: &'static str,
105    },
106    /// A value has no content at all, which Discord rejects β€” for example an embed with
107    /// nothing but a color.
108    Empty {
109        /// The path of the value, e.g. `embed`.
110        field: Cow<'static, str>,
111        /// What the value needs at least one of, for the error message.
112        needs: &'static str,
113    },
114}
115
116impl ValidationError {
117    /// Returns the path of the value that breaks the rule, e.g. `fields[3].name`.
118    ///
119    /// discord.js counterpart: none (the path inside a validation error of `@sapphire/shapeshift`).
120    ///
121    /// # Examples
122    ///
123    /// ```
124    /// use djs_builders::EmbedBuilder;
125    ///
126    /// let error = EmbedBuilder::new().field("ok", "y".repeat(2000)).build().unwrap_err();
127    /// assert_eq!(error.field(), "fields[0].value");
128    /// ```
129    #[must_use]
130    pub fn field(&self) -> &str {
131        match self {
132            Self::TooLong { field, .. }
133            | Self::TooMany { field, .. }
134            | Self::TooFew { field, .. }
135            | Self::Missing { field }
136            | Self::OutOfRange { field, .. }
137            | Self::InvalidUrl { field, .. }
138            | Self::InvalidName { field, .. }
139            | Self::Invalid { field, .. }
140            | Self::Empty { field, .. } => field,
141        }
142    }
143}
144
145impl fmt::Display for ValidationError {
146    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
147        match self {
148            Self::TooLong { field, max, actual } => write!(
149                f,
150                "{field} is too long: {actual} characters, at most {max} allowed"
151            ),
152            Self::TooMany { field, max, actual } => write!(
153                f,
154                "{field} has too many items: {actual}, at most {max} allowed"
155            ),
156            Self::TooFew { field, min, actual } => write!(
157                f,
158                "{field} has too few items: {actual}, at least {min} required"
159            ),
160            Self::Missing { field } => write!(f, "{field} is required"),
161            Self::OutOfRange {
162                field,
163                min,
164                max,
165                actual,
166            } => write!(
167                f,
168                "{field} is out of range: {actual} is not between {min} and {max}"
169            ),
170            Self::InvalidUrl { field, allowed } => {
171                write!(f, "{field} must start with ")?;
172                for (index, scheme) in allowed.iter().enumerate() {
173                    let separator = match index {
174                        0 => "",
175                        _ if index + 1 == allowed.len() => " or ",
176                        _ => ", ",
177                    };
178                    write!(f, "{separator}{scheme}")?;
179                }
180                Ok(())
181            }
182            Self::InvalidName { field, character } => {
183                let mut lower = character.to_lowercase();
184                if lower.len() == 1 && lower.next() == Some(*character) {
185                    write!(f, "{field} cannot contain {character:?}")
186                } else {
187                    write!(
188                        f,
189                        "{field} must be lower case: use '{}' instead of '{character}'",
190                        character.to_lowercase()
191                    )
192                }
193            }
194            Self::Invalid { field, reason } => write!(f, "{field} is invalid: {reason}"),
195            Self::Empty { field, needs } => {
196                write!(f, "{field} has no content: it needs {needs}")
197            }
198        }
199    }
200}
201
202impl std::error::Error for ValidationError {}
203
204#[cfg(test)]
205mod tests {
206    use super::ValidationError;
207
208    #[test]
209    fn every_variant_has_a_readable_message() {
210        let cases = [
211            (
212                ValidationError::TooMany {
213                    field: "fields".into(),
214                    max: 25,
215                    actual: 26,
216                },
217                "fields has too many items: 26, at most 25 allowed",
218            ),
219            (
220                ValidationError::TooFew {
221                    field: "components".into(),
222                    min: 1,
223                    actual: 0,
224                },
225                "components has too few items: 0, at least 1 required",
226            ),
227            (
228                ValidationError::Missing {
229                    field: "name".into(),
230                },
231                "name is required",
232            ),
233            (
234                ValidationError::OutOfRange {
235                    field: "color".into(),
236                    min: 0,
237                    max: 0xFF_FFFF,
238                    actual: 0x100_0000,
239                },
240                "color is out of range: 16777216 is not between 0 and 16777215",
241            ),
242            (
243                ValidationError::InvalidUrl {
244                    field: "url".into(),
245                    allowed: &["http://", "https://"],
246                },
247                "url must start with http:// or https://",
248            ),
249            (
250                ValidationError::InvalidUrl {
251                    field: "image.url".into(),
252                    allowed: &["http://", "https://", "attachment://"],
253                },
254                "image.url must start with http://, https:// or attachment://",
255            ),
256            (
257                ValidationError::InvalidName {
258                    field: "name".into(),
259                    character: 'Ε»',
260                },
261                "name must be lower case: use 'ΕΌ' instead of 'Ε»'",
262            ),
263            (
264                ValidationError::InvalidName {
265                    field: "options[0].name".into(),
266                    character: ' ',
267                },
268                "options[0].name cannot contain ' '",
269            ),
270            (
271                ValidationError::Invalid {
272                    field: "options[1].required".into(),
273                    reason: "required options must come before optional ones",
274                },
275                "options[1].required is invalid: required options must come before optional ones",
276            ),
277            (
278                ValidationError::Empty {
279                    field: "embed".into(),
280                    needs: "a title",
281                },
282                "embed has no content: it needs a title",
283            ),
284        ];
285        for (error, message) in cases {
286            assert_eq!(error.to_string(), message);
287            assert!(message.starts_with(error.field()));
288        }
289    }
290}