http/
error.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
use std::{
    borrow::Cow,
    fmt::{Debug, Display},
    io,
    num::ParseIntError,
    path::StripPrefixError,
    str::Utf8Error,
    string::FromUtf8Error,
};

/// Server Error
pub struct HttpError(Cow<'static, str>);

impl HttpError {
    /// Creates a [`ServerError`] from a &'static [str]
    #[inline]
    pub fn new(msg: impl Into<Cow<'static, str>>) -> Self {
        Self(msg.into())
    }
    /// Turns the [`ServerError`] into a [Result]<T`ServerError`or]>
    #[inline]
    pub fn err<T>(self) -> Result<T, Self> {
        Err(self)
    }
    /// Gets the message inside the [`ServerError`]
    #[inline]
    #[must_use]
    pub fn get_message(&self) -> &str {
        &self.0
    }
}

#[macro_export]
macro_rules! err {
    ($($e:tt)*) => {
        $crate::HttpError::new(format!($($e)*)).err()
    };
    ($lit:literal) => {
        $crate::HttpError::new($lit).err()
    };
    ($e:expr) => {
        $crate::HttpError::new($e).err()
    };
}

use regexpr::RegexError;

impl From<io::Error> for HttpError {
    #[inline]
    fn from(value: io::Error) -> Self {
        Self::new(value.to_string())
    }
}
impl From<FromUtf8Error> for HttpError {
    #[inline]
    fn from(value: FromUtf8Error) -> Self {
        Self::new(value.to_string())
    }
}
impl From<Utf8Error> for HttpError {
    #[inline]
    fn from(value: Utf8Error) -> Self {
        Self::new(value.to_string())
    }
}
impl From<std::path::StripPrefixError> for HttpError {
    #[inline]
    fn from(value: StripPrefixError) -> Self {
        Self::new(value.to_string())
    }
}
impl From<ParseIntError> for HttpError {
    #[inline]
    fn from(value: ParseIntError) -> Self {
        Self::new(value.to_string())
    }
}
impl From<Cow<'static, str>> for HttpError {
    #[inline]
    fn from(value: Cow<'static, str>) -> Self {
        Self(value)
    }
}

impl From<RegexError> for HttpError {
    fn from(value: RegexError) -> Self {
        Self::new(value.inner().clone())
    }
}

impl Debug for HttpError {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.get_message())
    }
}

impl Display for HttpError {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.get_message())
    }
}

impl From<&'static str> for HttpError {
    fn from(value: &'static str) -> Self {
        Self(value.into())
    }
}

impl From<String> for HttpError {
    fn from(value: String) -> Self {
        Self(value.into())
    }
}

impl std::error::Error for HttpError {}