Skip to main content

renox_core/
error.rs

1use axum::http::StatusCode;
2use axum::response::{Html, IntoResponse, Response};
3
4/// The result type handlers return; `Error` by default.
5pub type Result<T = (), E = Error> = std::result::Result<T, E>;
6
7/// The error type handlers return. Any `anyhow`-compatible error converts into
8/// `Error::Internal` with `?`.
9///
10/// For a status without its own variant (402, 409, 410, …) use
11/// `Error::Status`, or [`abort`] / [`abort_if`]:
12///
13/// ```
14/// # use renox::prelude::*;
15/// # struct Order { paid: bool }
16/// fn download(order: &Order) -> Result<&'static str> {
17///     renox::abort_if(!order.paid, StatusCode::PAYMENT_REQUIRED, "Pay for the order first.")?;
18///     Ok("the file")
19/// }
20/// ```
21#[non_exhaustive]
22pub enum Error {
23    /// 400, with a message that is safe to show visitors.
24    BadRequest(String),
25    /// 401: the request needs a logged-in user.
26    Unauthorized,
27    /// 403: the user may not do this.
28    Forbidden,
29    /// 404.
30    NotFound,
31    /// The CSRF token was missing or wrong, usually because the session expired.
32    PageExpired,
33    /// A rate limit was hit; see `Routes::throttle`.
34    TooManyRequests,
35    /// The app is in maintenance mode.
36    ServiceUnavailable,
37    /// Invalid input; see `ValidationError`.
38    Validation(crate::validation::ValidationError),
39    /// Any status, with a message that is safe to show visitors (on the
40    /// error page, or as `message` in JSON).
41    Status(StatusCode, String),
42    /// 500 (409 for a unique-constraint violation); details are shown only in debug.
43    Internal(anyhow::Error),
44}
45
46/// An error with `status` and a message shown to the visitor, for
47/// `return Err(abort(…))`. See [`abort_if`] for a condition.
48pub fn abort(status: StatusCode, message: impl Into<String>) -> Error {
49    Error::Status(status, message.into())
50}
51
52/// `Err(abort(status, message))` when `condition` holds, for `?`.
53pub fn abort_if(condition: bool, status: StatusCode, message: impl Into<String>) -> Result {
54    if condition {
55        Err(abort(status, message))
56    } else {
57        Ok(())
58    }
59}
60
61/// `Err(abort(status, message))` unless `condition` holds, for `?`.
62pub fn abort_unless(condition: bool, status: StatusCode, message: impl Into<String>) -> Result {
63    abort_if(!condition, status, message)
64}
65
66/// An error that retrying can't fix; see [`Error::permanent`]. It shows as
67/// the error it wraps, and stays findable in the chain under more context.
68#[derive(Debug)]
69struct Permanent(anyhow::Error);
70
71impl std::fmt::Display for Permanent {
72    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
73        std::fmt::Display::fmt(&self.0, f)
74    }
75}
76
77impl std::error::Error for Permanent {
78    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
79        self.0.chain().nth(1)
80    }
81}
82
83impl Error {
84    /// An error that retrying can't fix, e.g. an invalid email address. A job
85    /// that returns one goes to `failed_jobs` at once instead of being retried.
86    pub fn permanent(err: impl Into<anyhow::Error>) -> Self {
87        Self::Internal(anyhow::Error::new(Permanent(err.into())))
88    }
89
90    /// [`Error::permanent`] with just a message:
91    /// `Err(Error::permanent_message("the card was declined"))`.
92    pub fn permanent_message(message: impl std::fmt::Display) -> Self {
93        Self::permanent(anyhow::anyhow!("{message}"))
94    }
95
96    /// Whether the error was made with [`Error::permanent`].
97    pub fn is_permanent(&self) -> bool {
98        match self {
99            Self::Internal(err) => err.chain().any(|e| e.is::<Permanent>()),
100            _ => false,
101        }
102    }
103
104    /// Whether the error is a database conflict that retrying may clear (see
105    /// `DbError::is_retryable`).
106    pub fn is_retryable(&self) -> bool {
107        match self {
108            Self::Internal(err) => err.chain().any(|e| {
109                e.downcast_ref::<crate::db::DbError>()
110                    .is_some_and(crate::db::DbError::is_retryable)
111            }),
112            _ => false,
113        }
114    }
115
116    /// Whether the error is a database unique-constraint violation, e.g. a
117    /// second sign-up with the same email racing past the `unique` rule.
118    pub fn is_unique_violation(&self) -> bool {
119        match self {
120            Self::Internal(err) => err.chain().any(|e| {
121                e.downcast_ref::<crate::db::DbError>()
122                    .is_some_and(crate::db::DbError::is_unique_violation)
123                    || matches!(
124                        e.downcast_ref::<sqlx::Error>(),
125                        Some(sqlx::Error::Database(db)) if db.is_unique_violation()
126                    )
127            }),
128            _ => false,
129        }
130    }
131
132    /// The HTTP status this error responds with.
133    pub fn status(&self) -> StatusCode {
134        match self {
135            Self::BadRequest(_) => StatusCode::BAD_REQUEST,
136            Self::Unauthorized => StatusCode::UNAUTHORIZED,
137            Self::Forbidden => StatusCode::FORBIDDEN,
138            Self::NotFound => StatusCode::NOT_FOUND,
139            Self::PageExpired => StatusCode::from_u16(419).expect("valid status code"),
140            Self::TooManyRequests => StatusCode::TOO_MANY_REQUESTS,
141            Self::ServiceUnavailable => StatusCode::SERVICE_UNAVAILABLE,
142            Self::Validation(_) => StatusCode::UNPROCESSABLE_ENTITY,
143            Self::Status(status, _) => *status,
144            // A duplicate that got past validation (e.g. two requests at once).
145            Self::Internal(_) if self.is_unique_violation() => StatusCode::CONFLICT,
146            // A filter or sort on a sealed custom field is the visitor's doing.
147            Self::Internal(err)
148                if err.chain().any(|e| {
149                    e.downcast_ref::<crate::db::DbError>()
150                        .is_some_and(|d| d.sealed_custom_field_key().is_some())
151                }) =>
152            {
153                StatusCode::BAD_REQUEST
154            }
155            Self::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
156        }
157    }
158}
159
160/// Readable when `main` returns an error: the message and its causes.
161impl std::fmt::Debug for Error {
162    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
163        match self {
164            Self::Internal(err) => write!(f, "{err:?}"),
165            Self::BadRequest(msg) => write!(f, "bad request: {msg}"),
166            Self::Status(status, msg) => write!(f, "{}: {msg}", status.as_u16()),
167            Self::Validation(err) => write!(f, "validation failed: {:?}", err.errors),
168            other => write!(f, "{}", reason(other.status())),
169        }
170    }
171}
172
173/// The message alone, for logs and tests (`{}`): the error's own text
174/// without its causes (`{:?}` adds them), the message given to
175/// `abort`/`Error::Status`/`Error::BadRequest`, each field's messages for a
176/// validation error, else the status's reason ("Not Found").
177///
178/// ```
179/// # use renox::prelude::*;
180/// let err = renox::abort(StatusCode::CONFLICT, "The bike is already rented.");
181/// assert_eq!(err.to_string(), "The bike is already rented.");
182/// assert_eq!(Error::NotFound.to_string(), "Not Found");
183/// ```
184///
185/// `Error` doesn't implement `std::error::Error`: any error converts into it
186/// with `?`, and that conversion would then apply to `Error` itself.
187impl std::fmt::Display for Error {
188    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
189        match self {
190            Self::Internal(err) => write!(f, "{err}"),
191            Self::BadRequest(msg) | Self::Status(_, msg) => f.write_str(msg),
192            Self::Validation(err) => {
193                let mut first = true;
194                for (field, messages) in err.errors.iter() {
195                    for message in messages {
196                        if !first {
197                            f.write_str("; ")?;
198                        }
199                        first = false;
200                        write!(f, "{field}: {message}")?;
201                    }
202                }
203                if first {
204                    f.write_str(reason(self.status()))?;
205                }
206                Ok(())
207            }
208            other => f.write_str(reason(other.status())),
209        }
210    }
211}
212
213impl<E: Into<anyhow::Error>> From<E> for Error {
214    fn from(err: E) -> Self {
215        Self::Internal(err.into())
216    }
217}
218
219/// Marks an error response so the view middleware can render it with
220/// `errors/{status}.html` or the built-in `renox/error.html`.
221#[derive(Debug, Clone)]
222pub(crate) struct ErrorPage {
223    pub status: StatusCode,
224    /// Safe to show anyone, e.g. a bad request's message.
225    pub detail: Option<String>,
226    /// The internal error's chain, shown only when the app's `APP_DEBUG` is on.
227    pub debug_detail: Option<String>,
228    /// For a template error, where it happened with the lines around it;
229    /// shown only with `APP_DEBUG`.
230    pub template: Option<String>,
231}
232
233impl ErrorPage {
234    /// What to show on the page for an app with this debug setting.
235    pub fn shown_detail(&self, debug: bool) -> Option<&str> {
236        self.detail.as_deref().or(if debug {
237            self.debug_detail.as_deref()
238        } else {
239            None
240        })
241    }
242}
243
244impl ErrorPage {
245    /// The error as `{"message": …}` for API clients, with the same status.
246    pub fn json(&self, debug: bool) -> Response {
247        let message = self
248            .shown_detail(debug)
249            .unwrap_or_else(|| reason(self.status));
250        (
251            self.status,
252            axum::Json(serde_json::json!({ "message": message })),
253        )
254            .into_response()
255    }
256}
257
258/// Whether the client asked for JSON: `Accept: application/json`, or a JSON body.
259pub(crate) fn wants_json(headers: &axum::http::HeaderMap) -> bool {
260    let header = |name| headers.get(name).and_then(|v| v.to_str().ok());
261    header(axum::http::header::ACCEPT).is_some_and(|v| v.contains("application/json"))
262        || header(axum::http::header::CONTENT_TYPE)
263            .is_some_and(|v| v.starts_with("application/json"))
264}
265
266/// The text of a caught panic.
267pub(crate) fn panic_message(panic: &(dyn std::any::Any + Send)) -> String {
268    panic
269        .downcast_ref::<String>()
270        .cloned()
271        .or_else(|| panic.downcast_ref::<&str>().map(|s| (*s).to_owned()))
272        .unwrap_or_else(|| "(no message)".into())
273}
274
275pub(crate) fn reason(status: StatusCode) -> &'static str {
276    match status.as_u16() {
277        419 => "Page Expired",
278        _ => status.canonical_reason().unwrap_or("Error"),
279    }
280}
281
282impl From<crate::validation::ValidationError> for Error {
283    fn from(err: crate::validation::ValidationError) -> Self {
284        Self::Validation(err)
285    }
286}
287
288impl From<crate::validation::Errors> for Error {
289    fn from(errors: crate::validation::Errors) -> Self {
290        Self::Validation(errors.into())
291    }
292}
293
294impl IntoResponse for Error {
295    fn into_response(self) -> Response {
296        if let Self::Validation(err) = self {
297            return err.into_response();
298        }
299        let status = self.status();
300        let mut template = None;
301        let (detail, debug_detail) = match &self {
302            Self::Internal(err) => {
303                tracing::error!(error = ?err, "internal server error");
304                crate::report::request_error(err);
305                template = err
306                    .chain()
307                    .find_map(|e| e.downcast_ref::<minijinja::Error>())
308                    .map(|e| e.display_debug_info().to_string())
309                    .filter(|info| !info.trim().is_empty());
310                (None, Some(format!("{err:?}")))
311            }
312            Self::BadRequest(msg) => (Some(msg.clone()), None),
313            Self::Status(_, msg) if !msg.is_empty() => (Some(msg.clone()), None),
314            _ => (None, None),
315        };
316        // The view middleware renders the page, adding the internal detail
317        // only for apps in debug mode; this plain body never includes it.
318        let mut res = (status, Html(error_page(status, detail.as_deref()))).into_response();
319        res.extensions_mut().insert(ErrorPage {
320            status,
321            detail,
322            debug_detail,
323            template,
324        });
325        res
326    }
327}
328
329/// Plain page used without the view middleware or when the error template fails.
330pub(crate) fn error_page(status: StatusCode, detail: Option<&str>) -> String {
331    let code = status.as_u16();
332    let reason = reason(status);
333    let detail = detail
334        .map(|d| format!("<pre>{}</pre>", escape(d)))
335        .unwrap_or_default();
336    format!(
337        "<!doctype html><html><head><meta charset=\"utf-8\">\
338         <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\
339         <title>{code} {reason}</title></head>\
340         <body><h1>{code} · {reason}</h1>{detail}</body></html>"
341    )
342}
343
344fn escape(s: &str) -> String {
345    s.replace('&', "&amp;")
346        .replace('<', "&lt;")
347        .replace('>', "&gt;")
348        .replace('"', "&quot;")
349}
350
351#[cfg(test)]
352mod tests {
353    use super::*;
354
355    #[test]
356    fn validation_errors_answer_422_and_other_errors_500() {
357        let mut errors = crate::validation::Errors::new();
358        errors.add("name", "The name field is required.");
359        let err = Error::Validation(crate::validation::ValidationError::new(errors));
360        assert_eq!(err.status(), StatusCode::UNPROCESSABLE_ENTITY);
361        let plain = Error::from(anyhow::anyhow!("no database involved"));
362        assert!(!plain.is_unique_violation());
363        assert_eq!(plain.status(), StatusCode::INTERNAL_SERVER_ERROR);
364    }
365
366    /// A unique violation from sqlx itself (an app querying its pool
367    /// directly, then `?`) is a 409 like one from `renox::db`.
368    #[tokio::test]
369    async fn a_raw_sqlx_unique_violation_is_a_conflict() {
370        let db = crate::db::connect(&crate::Config::default()).await.unwrap();
371        let Some(pool) = db.sqlite() else {
372            return; // the PostgreSQL run: the same check, another driver
373        };
374        sqlx::raw_sql("CREATE TABLE tags (name TEXT UNIQUE); INSERT INTO tags VALUES ('a')")
375            .execute(pool)
376            .await
377            .unwrap();
378        let raw = sqlx::raw_sql("INSERT INTO tags VALUES ('a')")
379            .execute(pool)
380            .await
381            .unwrap_err();
382        let err = Error::from(anyhow::Error::new(raw));
383        assert!(err.is_unique_violation());
384        assert_eq!(err.status(), StatusCode::CONFLICT);
385    }
386}