1use axum::http::StatusCode;
2use axum::response::{Html, IntoResponse, Response};
3
4pub type Result<T = (), E = Error> = std::result::Result<T, E>;
6
7#[non_exhaustive]
22pub enum Error {
23 BadRequest(String),
25 Unauthorized,
27 Forbidden,
29 NotFound,
31 PageExpired,
33 TooManyRequests,
35 ServiceUnavailable,
37 Validation(crate::validation::ValidationError),
39 Status(StatusCode, String),
42 Internal(anyhow::Error),
44}
45
46pub fn abort(status: StatusCode, message: impl Into<String>) -> Error {
49 Error::Status(status, message.into())
50}
51
52pub 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
61pub fn abort_unless(condition: bool, status: StatusCode, message: impl Into<String>) -> Result {
63 abort_if(!condition, status, message)
64}
65
66#[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 pub fn permanent(err: impl Into<anyhow::Error>) -> Self {
87 Self::Internal(anyhow::Error::new(Permanent(err.into())))
88 }
89
90 pub fn permanent_message(message: impl std::fmt::Display) -> Self {
93 Self::permanent(anyhow::anyhow!("{message}"))
94 }
95
96 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 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 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 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 Self::Internal(_) if self.is_unique_violation() => StatusCode::CONFLICT,
146 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
160impl 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
173impl 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#[derive(Debug, Clone)]
222pub(crate) struct ErrorPage {
223 pub status: StatusCode,
224 pub detail: Option<String>,
226 pub debug_detail: Option<String>,
228 pub template: Option<String>,
231}
232
233impl ErrorPage {
234 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 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
258pub(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
266pub(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 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
329pub(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('&', "&")
346 .replace('<', "<")
347 .replace('>', ">")
348 .replace('"', """)
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 #[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; };
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}