http_srv/server/
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
use std::{borrow::Cow, fmt::{Debug, Display}, io, num::ParseIntError, path::StripPrefixError, string::FromUtf8Error};

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

impl ServerError {
    /// 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_rules! err {
    ($($e:tt)*) => {
        crate::ServerError::new(format!($($e)*)).err()
    };
    ($lit:literal) => {
        crate::ServerError::new($lit).err()
    };
    ($e:expr) => {
        crate::ServerError::new($e).err()
    };
}

pub (crate) use err;

impl From<io::Error> for ServerError {
    #[inline]
    fn from(value: io::Error) -> Self {
        Self::new(value.to_string())
    }
}
impl From<FromUtf8Error> for ServerError {
    #[inline]
    fn from(value: FromUtf8Error) -> Self {
        Self::new(value.to_string())
    }
}
impl From<std::path::StripPrefixError> for ServerError {
    #[inline]
    fn from(value: StripPrefixError) -> Self {
        Self::new(value.to_string())
    }
}
impl From<ParseIntError> for ServerError {
    #[inline]
    fn from(value: ParseIntError) -> Self {
        Self::new(value.to_string())
    }
}
impl From<Cow<'static,str>> for ServerError {
    #[inline]
    fn from(value: Cow<'static,str>) -> Self {
        Self(value)
    }
}
impl Debug for ServerError {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
       write!(f, "{}", self.get_message())
    }
}

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

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

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

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