Skip to main content

glacier/
error.rs

1//! The error type shared across Glacier.
2
3use std::fmt;
4
5use http::StatusCode;
6
7use crate::response::{IntoResponse, Response};
8
9/// `-> Result` in a handler means `-> Result<Response>`.
10pub type Result<T = Response, E = Error> = std::result::Result<T, E>;
11
12type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
13
14/// An error carrying the HTTP status it should be rendered with.
15///
16/// Any `std::error::Error` converts into a `500 Internal Server Error` via `?`,
17/// so handlers can bubble failures up without ceremony. Use the constructors
18/// (`Error::not_found()`, `Error::bad_request(..)`, ...) for client errors.
19///
20/// Like `anyhow::Error`, this type deliberately does not implement
21/// `std::error::Error` itself; that is what makes the blanket `From` possible.
22pub struct Error {
23    status: StatusCode,
24    message: String,
25    source: Option<BoxError>,
26}
27
28impl Error {
29    pub fn new(status: StatusCode, message: impl Into<String>) -> Self {
30        Self {
31            status,
32            message: message.into(),
33            source: None,
34        }
35    }
36
37    /// An error with `source` as its cause, kept for
38    /// [`downcast_ref`](Self::downcast_ref) and the logs.
39    pub fn with_source(
40        status: StatusCode,
41        message: impl Into<String>,
42        source: impl std::error::Error + Send + Sync + 'static,
43    ) -> Self {
44        Self {
45            status,
46            message: message.into(),
47            source: Some(Box::new(source)),
48        }
49    }
50
51    /// The cause, if it's an `E`: `err.downcast_ref::<ClientError>()`
52    /// says why a call to another service failed.
53    pub fn downcast_ref<E: std::error::Error + 'static>(&self) -> Option<&E> {
54        self.source.as_deref()?.downcast_ref::<E>()
55    }
56
57    pub fn not_found() -> Self {
58        Self::new(StatusCode::NOT_FOUND, "Not Found")
59    }
60
61    /// `403 Forbidden`: signed in, but not allowed to do this.
62    pub fn forbidden() -> Self {
63        Self::new(StatusCode::FORBIDDEN, "Forbidden")
64    }
65
66    pub fn bad_request(message: impl Into<String>) -> Self {
67        Self::new(StatusCode::BAD_REQUEST, message)
68    }
69
70    pub fn unprocessable(message: impl Into<String>) -> Self {
71        Self::new(StatusCode::UNPROCESSABLE_ENTITY, message)
72    }
73
74    pub fn internal(message: impl Into<String>) -> Self {
75        Self::new(StatusCode::INTERNAL_SERVER_ERROR, message)
76    }
77
78    pub fn status(&self) -> StatusCode {
79        self.status
80    }
81
82    pub fn message(&self) -> &str {
83        &self.message
84    }
85
86    /// The underlying error, if this was converted from one.
87    pub fn source(&self) -> Option<&(dyn std::error::Error + Send + Sync + 'static)> {
88        self.source.as_deref()
89    }
90}
91
92impl<E> From<E> for Error
93where
94    E: std::error::Error + Send + Sync + 'static,
95{
96    fn from(err: E) -> Self {
97        Self {
98            status: StatusCode::INTERNAL_SERVER_ERROR,
99            message: err.to_string(),
100            source: Some(Box::new(err)),
101        }
102    }
103}
104
105/// Readable when `main` returns an error; `{:#?}` shows the raw fields.
106impl fmt::Debug for Error {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        if f.alternate() {
109            return f
110                .debug_struct("Error")
111                .field("status", &self.status)
112                .field("message", &self.message)
113                .field("source", &self.source)
114                .finish();
115        }
116        write!(f, "{}", self.message)?;
117        let mut source = self.source.as_deref().and_then(|err| err.source());
118        if source.is_some() {
119            write!(f, "\n\nCaused by:")?;
120        }
121        while let Some(err) = source {
122            write!(f, "\n    {err}")?;
123            source = err.source();
124        }
125        Ok(())
126    }
127}
128
129impl fmt::Display for Error {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        write!(f, "{}: {}", self.status, self.message)
132    }
133}
134
135/// Details of a server error, attached to the response's extensions so the
136/// development error page can show them. Never sent to clients as-is.
137#[derive(Debug, Clone)]
138pub struct ErrorReport {
139    pub status: StatusCode,
140    pub message: String,
141    /// `source()` chain of the underlying error, outermost first.
142    pub causes: Vec<String>,
143}
144
145/// Marks an error response with no body of its own, just its status line
146/// (`Not Found`), so the app can answer it in the format the request asked
147/// for, as Rails' public exceptions do. A body the app shaped itself, such
148/// as [`JsonErrors`](crate::middleware::JsonErrors)', has no mark.
149#[derive(Debug, Clone, Copy)]
150pub(crate) struct Bare;
151
152impl IntoResponse for Error {
153    fn into_response(self) -> Response {
154        if self.status.is_server_error() {
155            let mut causes = Vec::new();
156            let mut source = self.source.as_deref().and_then(|err| err.source());
157            while let Some(err) = source {
158                causes.push(err.to_string());
159                source = err.source();
160            }
161            // Never leak internal details to the client; log them instead,
162            // inside the request's span.
163            tracing::event!(
164                target: "glacier",
165                tracing::Level::ERROR,
166                http.response.status_code = i64::from(self.status.as_u16()),
167                error.message = %self.message,
168                error.causes = ?causes,
169                "request failed: {}",
170                self.message
171            );
172            let reason = self.status.canonical_reason().unwrap_or("Error");
173            let mut res = Response::text(reason).with_status(self.status);
174            res.extensions_mut().insert(Bare);
175            res.extensions_mut().insert(ErrorReport {
176                status: self.status,
177                message: self.message,
178                causes,
179            });
180            res
181        } else {
182            let bare = Some(self.message.as_str()) == self.status.canonical_reason();
183            let mut res = Response::text(self.message).with_status(self.status);
184            if bare {
185                res.extensions_mut().insert(Bare);
186            }
187            res
188        }
189    }
190}