cookie_monster/
error.rs

1use std::fmt::Display;
2
3/// All errors that can be returned while parsing or serializing cookies.
4#[derive(Debug, PartialEq, Eq)]
5#[non_exhaustive]
6pub enum Error {
7    /// No '=' found in the cookie string.
8    EqualsNotFound,
9    /// Name value is empty.
10    NameEmpty,
11    /// Name contains invalid character.
12    InvalidName(char),
13    /// Value contains invalid character.
14    InvalidValue(char),
15
16    /// Unable to format the expires field.
17    ExpiresFmt,
18
19    /// Could not percent-decode the cookie.
20    PercentDecodeError,
21
22    /// Path attribute contains an invalid character.
23    InvalidPathValue(char),
24    /// Path attribute value is empty.
25    EmptyPathValue,
26    /// Path does not start with a leading '/'.
27    NoLeadingSlash,
28}
29
30impl Display for Error {
31    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32        let err = match self {
33            Error::EqualsNotFound => "No '=' found in the cookie",
34            Error::NameEmpty => "The cookie name is empty",
35            Error::InvalidName(c) => {
36                return write!(f, "The cookie name contains an invalid character: {c}");
37            }
38            Error::InvalidValue(c) => {
39                return write!(f, "The cookie value contains an invalid character: {c}");
40            }
41            Error::ExpiresFmt => "Failed to format the expires value",
42            Error::PercentDecodeError => "An error occurred while decoding",
43            Error::InvalidPathValue(c) => {
44                return write!(f, "The path attribute contains an invalid character ({c})");
45            }
46            Error::EmptyPathValue => "The path attribute is empty",
47            Error::NoLeadingSlash => "The path attribute does not start with a leading slash",
48        };
49
50        f.write_str(err)
51    }
52}
53
54impl std::error::Error for Error {}