1use std::{
2 borrow::Cow,
3 fmt::{Debug, Display},
4 io,
5 num::ParseIntError,
6 path::StripPrefixError,
7 str::Utf8Error,
8 string::FromUtf8Error,
9};
10
11pub struct HttpError(Cow<'static, str>);
13
14impl HttpError {
15 #[inline]
17 pub fn new(msg: impl Into<Cow<'static, str>>) -> Self {
18 Self(msg.into())
19 }
20 #[inline]
22 pub fn err<T>(self) -> Result<T, Self> {
23 Err(self)
24 }
25 #[inline]
27 #[must_use]
28 pub fn get_message(&self) -> &str {
29 &self.0
30 }
31}
32
33#[macro_export]
34macro_rules! err {
35 ($($e:tt)*) => {
36 $crate::HttpError::new(format!($($e)*)).err()
37 };
38 ($lit:literal) => {
39 $crate::HttpError::new($lit).err()
40 };
41 ($e:expr) => {
42 $crate::HttpError::new($e).err()
43 };
44}
45
46impl From<io::Error> for HttpError {
47 #[inline]
48 fn from(value: io::Error) -> Self {
49 Self::new(value.to_string())
50 }
51}
52impl From<FromUtf8Error> for HttpError {
53 #[inline]
54 fn from(value: FromUtf8Error) -> Self {
55 Self::new(value.to_string())
56 }
57}
58impl From<Utf8Error> for HttpError {
59 #[inline]
60 fn from(value: Utf8Error) -> Self {
61 Self::new(value.to_string())
62 }
63}
64impl From<std::path::StripPrefixError> for HttpError {
65 #[inline]
66 fn from(value: StripPrefixError) -> Self {
67 Self::new(value.to_string())
68 }
69}
70impl From<ParseIntError> for HttpError {
71 #[inline]
72 fn from(value: ParseIntError) -> Self {
73 Self::new(value.to_string())
74 }
75}
76impl From<Cow<'static, str>> for HttpError {
77 #[inline]
78 fn from(value: Cow<'static, str>) -> Self {
79 Self(value)
80 }
81}
82
83impl Debug for HttpError {
84 #[inline]
85 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
86 write!(f, "{}", self.get_message())
87 }
88}
89
90impl Display for HttpError {
91 #[inline]
92 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
93 write!(f, "{}", self.get_message())
94 }
95}
96
97impl From<&'static str> for HttpError {
98 fn from(value: &'static str) -> Self {
99 Self(value.into())
100 }
101}
102
103impl From<String> for HttpError {
104 fn from(value: String) -> Self {
105 Self(value.into())
106 }
107}
108
109impl std::error::Error for HttpError {}