1use axum::{
4 extract::rejection::JsonRejection,
5 http::{
6 header::{InvalidHeaderName, InvalidHeaderValue},
7 method::InvalidMethod,
8 StatusCode,
9 },
10};
11#[cfg(feature = "mailer")]
12use lettre::{address::AddressError, transport::smtp};
13
14use crate::{controller::ErrorDetail, depcheck, validation::ModelValidationErrors};
15
16impl From<serde_json::Error> for Error {
26 fn from(val: serde_json::Error) -> Self {
27 Self::JSON(val).bt()
28 }
29}
30
31#[derive(thiserror::Error, Debug)]
52#[non_exhaustive]
53pub enum Error {
54 #[error("{0}")]
56 Message(String),
57
58 #[error("{0}")]
60 Unauthorized(String),
61
62 #[error("not found")]
64 NotFound,
65
66 #[error("{0}")]
67 BadRequest(String),
68
69 #[error("")]
70 CustomError(StatusCode, ErrorDetail),
71
72 #[error("internal server error")]
73 InternalServerError,
74
75 #[error(transparent)]
76 JsonRejection(#[from] JsonRejection),
77
78 #[error(transparent)]
79 AxumFormRejection(#[from] axum::extract::rejection::FormRejection),
80
81 #[error(transparent)]
82 Validation(#[from] ModelValidationErrors),
83
84 #[cfg(feature = "with-db")]
85 #[error(transparent)]
87 Model(#[from] crate::model::ModelError),
88
89 #[error("{inner}\n{backtrace}")]
91 WithBacktrace {
92 inner: Box<Self>,
93 backtrace: Box<std::backtrace::Backtrace>,
94 },
95
96 #[error(
97 "error while running worker: no queue provider populated in context. Did you configure \
98 BackgroundQueue and connection details in `queue` in your config file?"
99 )]
100 QueueProviderMissing,
101
102 #[error("task not found: '{0}'")]
103 TaskNotFound(String),
104
105 #[error(transparent)]
106 Scheduler(#[from] crate::scheduler::Error),
107
108 #[error(transparent)]
109 Axum(#[from] axum::http::Error),
110
111 #[error(transparent)]
112 Tera(#[from] tera::Error),
113
114 #[error(transparent)]
115 JSON(serde_json::Error),
116
117 #[error("cannot parse `{1}`: {0}")]
118 YAMLFile(#[source] serde_yaml::Error, String),
119
120 #[error(transparent)]
121 YAML(#[from] serde_yaml::Error),
122
123 #[cfg(feature = "mailer")]
124 #[error("Error sending email: '{0}'")]
125 EmailSender(#[from] lettre::error::Error),
126
127 #[cfg(feature = "mailer")]
128 #[error("Error sending email (smtp): '{0}'")]
129 Smtp(#[from] smtp::Error),
130
131 #[error("Worker error: {0}")]
132 Worker(String),
133
134 #[error(transparent)]
135 IO(#[from] std::io::Error),
136
137 #[cfg(feature = "with-db")]
138 #[error(transparent)]
139 DB(#[from] sea_orm::DbErr),
140
141 #[cfg(feature = "mailer")]
142 #[error(transparent)]
143 ParseAddress(#[from] AddressError),
144
145 #[error(transparent)]
146 InvalidHeaderValue(#[from] InvalidHeaderValue),
147
148 #[error(transparent)]
149 InvalidHeaderName(#[from] InvalidHeaderName),
150
151 #[error(transparent)]
152 InvalidMethod(#[from] InvalidMethod),
153
154 #[cfg(feature = "worker_redis")]
155 #[error(transparent)]
156 Redis(#[from] redis::RedisError),
157
158 #[cfg(feature = "worker")]
159 #[error(transparent)]
160 Sqlx(#[from] sqlx::Error),
161
162 #[error(transparent)]
163 Storage(#[from] crate::storage::StorageError),
164
165 #[error(transparent)]
166 Cache(#[from] crate::cache::CacheError),
167
168 #[cfg(all(debug_assertions, feature = "generators"))]
169 #[error(transparent)]
170 Generators(#[from] loco_gen::Error),
171
172 #[error(transparent)]
173 VersionCheck(#[from] depcheck::VersionCheckError),
174
175 #[error(transparent)]
176 Any(#[from] Box<dyn std::error::Error + Send + Sync>),
177}
178
179impl Error {
180 pub fn wrap(err: impl std::error::Error + Send + Sync + 'static) -> Self {
181 Self::Any(Box::new(err)) }
183
184 pub fn msg(err: impl std::error::Error + Send + Sync + 'static) -> Self {
185 Self::Message(err.to_string()) }
187 #[must_use]
188 pub fn string(s: &str) -> Self {
189 Self::Message(s.to_string())
190 }
191 #[must_use]
192 pub fn bt(self) -> Self {
193 let backtrace = std::backtrace::Backtrace::capture();
194 match backtrace.status() {
195 std::backtrace::BacktraceStatus::Disabled
196 | std::backtrace::BacktraceStatus::Unsupported => self,
197 _ => Self::WithBacktrace {
198 inner: Box::new(self),
199 backtrace: Box::new(backtrace),
200 },
201 }
202 }
203}
204
205#[derive(Debug)]
208struct Contextual {
209 msg: String,
210 source: Option<Box<dyn std::error::Error + Send + Sync>>,
211}
212
213impl std::fmt::Display for Contextual {
214 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
215 f.write_str(&self.msg)
216 }
217}
218
219impl std::error::Error for Contextual {
220 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
221 self.source
222 .as_deref()
223 .map(|e| e as &(dyn std::error::Error + 'static))
224 }
225}
226
227pub trait OrErr<T> {
254 fn or_err(self, msg: impl Into<String>) -> crate::Result<T>;
258
259 fn or_err_with<S: Into<String>>(self, f: impl FnOnce() -> S) -> crate::Result<T>;
264}
265
266impl<T, E> OrErr<T> for std::result::Result<T, E>
267where
268 E: std::error::Error + Send + Sync + 'static,
269{
270 fn or_err(self, msg: impl Into<String>) -> crate::Result<T> {
271 self.or_err_with(|| msg)
272 }
273
274 fn or_err_with<S: Into<String>>(self, f: impl FnOnce() -> S) -> crate::Result<T> {
275 self.map_err(|source| {
276 Error::wrap(Contextual {
277 msg: f().into(),
278 source: Some(Box::new(source)),
279 })
280 })
281 }
282}
283
284impl<T> OrErr<T> for Option<T> {
285 fn or_err(self, msg: impl Into<String>) -> crate::Result<T> {
286 self.or_err_with(|| msg)
287 }
288
289 fn or_err_with<S: Into<String>>(self, f: impl FnOnce() -> S) -> crate::Result<T> {
290 self.ok_or_else(|| {
291 Error::wrap(Contextual {
292 msg: f().into(),
293 source: None,
294 })
295 })
296 }
297}
298
299#[cfg(test)]
300mod or_err_tests {
301
302 use super::*;
303
304 #[test]
305 fn result_keeps_source_chain() {
306 let err = "x".parse::<u8>().or_err("bad number").unwrap_err();
307 assert_eq!(err.to_string(), "bad number");
308 let Error::Any(inner) = &err else {
309 panic!("expected Error::Any, got {err:?}")
310 };
311 let cause = inner.source().expect("source preserved");
312 assert!(cause.is::<std::num::ParseIntError>());
313 }
314
315 #[test]
316 fn option_none_has_message_and_no_source() {
317 let err = None::<u8>.or_err("missing").unwrap_err();
318 assert_eq!(err.to_string(), "missing");
319 let Error::Any(inner) = &err else {
320 panic!("expected Error::Any")
321 };
322 assert!(inner.source().is_none());
323 }
324
325 #[test]
326 fn ok_values_pass_through_and_lazy_message_is_not_built() {
327 assert_eq!("7".parse::<u8>().or_err("no").unwrap(), 7);
328 assert_eq!(
329 Some(1)
330 .or_err_with(|| -> String { panic!("built eagerly") })
331 .unwrap(),
332 1
333 );
334 }
335
336 #[test]
337 fn lazy_message_on_failure() {
338 let err = None::<u8>.or_err_with(|| format!("id {}", 3)).unwrap_err();
339 assert_eq!(err.to_string(), "id 3");
340 }
341}