Skip to main content

loco_rs/
errors.rs

1//! # Application Error Handling
2
3use 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
16/*
17backtrace principles:
18- use a plan warapper variant with no 'from' conversion
19- hand-code "From" conversion and force capture there with 'bt', which
20  will wrap and create backtrace only if RUST_BACKTRACE=1.
21costs:
22- when RUST_BACKTRACE is not set, we don't pay for the capture and we dont pay for printing.
23
24 */
25impl From<serde_json::Error> for Error {
26    fn from(val: serde_json::Error) -> Self {
27        Self::JSON(val).bt()
28    }
29}
30
31/// Application-wide error type.
32///
33/// Variants are grouped into two regions, in this fixed order:
34///
35/// 1. **Client-facing / API errors** — conditions that are meaningful to an
36///    API caller and are mapped, one by one, to a specific status code by
37///    `impl IntoResponse for Error` (see `controller::mod`). This includes
38///    [`Error::Model`], since [`crate::model::ModelError`] variants
39///    (`EntityNotFound`, `EntityAlreadyExists`, `Validation`) map to distinct
40///    client statuses.
41/// 2. **Internal / infrastructure errors** — everything else (I/O, DB,
42///    queue, template rendering, email, etc.). These do not leak details to
43///    callers and are deliberately collapsed to a generic `500 Internal
44///    Server Error` by the same `IntoResponse` impl, via explicit (not
45///    wildcard) match arms so the compiler forces every new variant to be
46///    classified into one of the two regions.
47///
48/// This grouping is purely organizational: variant names, `#[error(...)]`
49/// messages, `#[from]` conversions, and `#[cfg(...)]` gates are unchanged,
50/// so it is not a breaking change.
51#[derive(thiserror::Error, Debug)]
52#[non_exhaustive]
53pub enum Error {
54    // ─────────────────────────── Client-facing / API errors ───────────────────────────
55    #[error("{0}")]
56    Message(String),
57
58    // API
59    #[error("{0}")]
60    Unauthorized(String),
61
62    // API
63    #[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    // Model
86    #[error(transparent)]
87    Model(#[from] crate::model::ModelError),
88
89    // ─────────────────────────── Internal / infrastructure errors ─────────────────────
90    #[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)) //.bt()
182    }
183
184    pub fn msg(err: impl std::error::Error + Send + Sync + 'static) -> Self {
185        Self::Message(err.to_string()) //.bt()
186    }
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/// An error with a message of your own on top of the one that caused it.
206/// Display shows the message; the cause stays reachable through `source()`.
207#[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
227/// Turn a foreign `Result` or `Option` into a [`crate::Result`] with a message
228/// of your own, so `?` works without a hand-written `map_err`.
229///
230/// ```
231/// use loco_rs::prelude::*;
232///
233/// fn port(raw: &str) -> Result<u16> {
234///     raw.parse::<u16>().or_err("invalid port")
235/// }
236///
237/// fn first(items: &[u8]) -> Result<u8> {
238///     items.first().copied().or_err("no items")
239/// }
240///
241/// assert_eq!(port("80").unwrap(), 80);
242/// assert_eq!(port("x").unwrap_err().to_string(), "invalid port");
243/// assert_eq!(first(&[]).unwrap_err().to_string(), "no items");
244/// ```
245///
246/// For a `Result` the original error is kept as the `source()` of the new one,
247/// so logs and `std::error::Error::source` walkers still see the whole chain.
248/// The result is [`Error::Any`], which responds with a generic `500`; use
249/// `Error::BadRequest` and friends when the caller should see the message.
250///
251/// The method is named `or_err` rather than `context` so it never collides
252/// with `anyhow::Context` when both are in scope.
253pub trait OrErr<T> {
254    /// # Errors
255    /// Returns [`Error::Any`] carrying `msg`, with the original error as its
256    /// source when there is one.
257    fn or_err(self, msg: impl Into<String>) -> crate::Result<T>;
258
259    /// Like [`OrErr::or_err`], but the message is built only on failure.
260    ///
261    /// # Errors
262    /// Same as [`OrErr::or_err`].
263    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}