bws_web_server/core/error/
mod.rs1use std::fmt;
7use std::io;
8
9#[derive(Debug)]
11pub enum BwsError {
12 Io(io::Error),
14
15 Config(String),
17
18 Certificate(String),
20
21 Http(String),
23
24 Proxy(String),
26
27 Auth(String),
29
30 Internal(String),
32
33 Validation(String),
35
36 NotFound(String),
38
39 RateLimit(String),
41}
42
43impl fmt::Display for BwsError {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 match self {
46 BwsError::Io(err) => write!(f, "IO error: {}", err),
47 BwsError::Config(msg) => write!(f, "Configuration error: {}", msg),
48 BwsError::Certificate(msg) => write!(f, "Certificate error: {}", msg),
49 BwsError::Http(msg) => write!(f, "HTTP error: {}", msg),
50 BwsError::Proxy(msg) => write!(f, "Proxy error: {}", msg),
51 BwsError::Auth(msg) => write!(f, "Authentication error: {}", msg),
52 BwsError::Internal(msg) => write!(f, "Internal error: {}", msg),
53 BwsError::Validation(msg) => write!(f, "Validation error: {}", msg),
54 BwsError::NotFound(msg) => write!(f, "Not found: {}", msg),
55 BwsError::RateLimit(msg) => write!(f, "Rate limit exceeded: {}", msg),
56 }
57 }
58}
59
60impl std::error::Error for BwsError {
61 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
62 match self {
63 BwsError::Io(err) => Some(err),
64 _ => None,
65 }
66 }
67}
68
69impl From<io::Error> for BwsError {
70 fn from(err: io::Error) -> Self {
71 BwsError::Io(err)
72 }
73}
74
75impl From<pingora::Error> for BwsError {
76 fn from(err: pingora::Error) -> Self {
77 BwsError::Http(format!("Pingora error: {}", err))
78 }
79}
80
81pub type BwsResult<T> = Result<T, BwsError>;
83
84pub trait ErrorContext<T> {
86 fn with_context<F>(self, f: F) -> BwsResult<T>
88 where
89 F: FnOnce() -> String;
90}
91
92impl<T, E> ErrorContext<T> for Result<T, E>
93where
94 E: Into<BwsError>,
95{
96 fn with_context<F>(self, f: F) -> BwsResult<T>
97 where
98 F: FnOnce() -> String,
99 {
100 self.map_err(|e| {
101 let base_error = e.into();
102 let context = f();
103
104 match base_error {
105 BwsError::Internal(msg) => BwsError::Internal(format!("{}: {}", context, msg)),
106 other => BwsError::Internal(format!("{}: {}", context, other)),
107 }
108 })
109 }
110}
111
112#[macro_export]
114macro_rules! config_error {
115 ($($arg:tt)*) => {
116 BwsError::Config(format!($($arg)*))
117 };
118}
119
120#[macro_export]
122macro_rules! cert_error {
123 ($($arg:tt)*) => {
124 BwsError::Certificate(format!($($arg)*))
125 };
126}
127
128#[macro_export]
130macro_rules! http_error {
131 ($($arg:tt)*) => {
132 BwsError::Http(format!($($arg)*))
133 };
134}
135
136#[macro_export]
138macro_rules! validation_error {
139 ($($arg:tt)*) => {
140 BwsError::Validation(format!($($arg)*))
141 };
142}