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