error.rs
⎇
Raw
1use std::path::PathBuf;
2use std::sync::Arc;
3
4use axum::http::StatusCode;
5use axum::response::{IntoResponse, Response};
6
7use crate::db::Db;
8
9#[derive(Clone)]
10pub struct AppState {
11 pub db: Db,
12 /// Canonicalized server root folder.
13 pub root: PathBuf,
14 /// What the UI calls the root folder (`--root-name`, else its file name).
15 pub root_name: String,
16 /// Whether we sit behind a TLS-terminating reverse proxy.
17 pub https: bool,
18 /// Thumbnail cache. `None` when `--cache` is unset, which turns
19 /// thumbnails off everywhere.
20 pub thumbs: Option<Arc<crate::thumb::Thumbs>>,
21}
22
23/// API error. `extra` is optionally merged into the JSON body (e.g. a list of
24/// conflicting file names on a 409). `code`, when present, is a stable
25/// machine-readable identifier the client maps to a localized message (the
26/// English text stays for logs and non-localized clients). Rendered by
27/// `IntoResponse` below; the error string itself is never displayed, so no
28/// `Display` impl is needed.
29pub struct ApiError(
30 pub StatusCode,
31 pub String,
32 pub Option<serde_json::Value>,
33 pub Option<&'static str>,
34);
35
36impl ApiError {
37 pub fn new(status: StatusCode, msg: impl Into<String>) -> Self {
38 Self(status, msg.into(), None, None)
39 }
40
41 /// A user-facing error with a stable `code` for client-side
42 /// localization (the code doubles as the i18n key).
43 pub fn localized(status: StatusCode, msg: impl Into<String>, code: &'static str) -> Self {
44 Self(status, msg.into(), None, Some(code))
45 }
46
47 pub fn with_extra(mut self, extra: serde_json::Value) -> Self {
48 self.2 = Some(extra);
49 self
50 }
51}
52
53impl IntoResponse for ApiError {
54 fn into_response(self) -> Response {
55 let mut body = serde_json::json!({ "error": self.1 });
56 if let Some(code) = self.3 {
57 body["code"] = serde_json::json!(code);
58 }
59 if let Some(extra) = self.2
60 && let (Some(obj), Some(extra)) = (body.as_object_mut(), extra.as_object())
61 {
62 for (k, v) in extra {
63 obj.insert(k.clone(), v.clone());
64 }
65 }
66 (self.0, axum::Json(body)).into_response()
67 }
68}
69
70impl From<std::io::Error> for ApiError {
71 fn from(e: std::io::Error) -> Self {
72 tracing::error!(error = %e, "io error");
73 ApiError::localized(
74 StatusCode::INTERNAL_SERVER_ERROR,
75 "internal error",
76 "err_internal",
77 )
78 }
79}
80
81impl From<rusqlite::Error> for ApiError {
82 fn from(e: rusqlite::Error) -> Self {
83 tracing::error!(error = %e, "database error");
84 ApiError::localized(
85 StatusCode::INTERNAL_SERVER_ERROR,
86 "internal error",
87 "err_internal",
88 )
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95 use axum::http::StatusCode;
96 use http_body_util::BodyExt;
97
98 fn status_and_body(e: ApiError) -> (StatusCode, String) {
99 let resp = e.into_response();
100 let status = resp.status();
101 let rt = tokio::runtime::Builder::new_current_thread()
102 .enable_all()
103 .build()
104 .unwrap();
105 let bytes = rt
106 .block_on(async { resp.into_body().collect().await.unwrap().to_bytes() })
107 .to_vec();
108 (status, String::from_utf8(bytes).unwrap())
109 }
110
111 #[test]
112 fn plain_error_body() {
113 let (status, body) =
114 status_and_body(ApiError::new(StatusCode::NOT_FOUND, "folder not found"));
115 assert_eq!(status, StatusCode::NOT_FOUND);
116 assert_eq!(
117 serde_json::from_str::<serde_json::Value>(&body).unwrap(),
118 serde_json::json!({ "error": "folder not found" })
119 );
120 }
121
122 #[test]
123 fn extra_object_is_merged_into_body() {
124 let e = ApiError::new(StatusCode::CONFLICT, "some files already exist")
125 .with_extra(serde_json::json!({ "skipped": ["a.txt"], "uploaded": 2 }));
126 let (status, body) = status_and_body(e);
127 assert_eq!(status, StatusCode::CONFLICT);
128 assert_eq!(
129 serde_json::from_str::<serde_json::Value>(&body).unwrap(),
130 serde_json::json!({
131 "error": "some files already exist",
132 "skipped": ["a.txt"],
133 "uploaded": 2
134 })
135 );
136 }
137
138 #[test]
139 fn non_object_extra_is_ignored() {
140 let e = ApiError::new(StatusCode::CONFLICT, "conflict")
141 .with_extra(serde_json::json!(["not", "an", "object"]));
142 let (_status, body) = status_and_body(e);
143 assert_eq!(
144 serde_json::from_str::<serde_json::Value>(&body).unwrap(),
145 serde_json::json!({ "error": "conflict" })
146 );
147 }
148
149 #[test]
150 fn io_error_maps_to_500() {
151 let e = ApiError::from(std::io::Error::new(
152 std::io::ErrorKind::NotFound,
153 "disk vanished",
154 ));
155 let (status, body) = status_and_body(e);
156 assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
157 assert!(body.contains("internal error"));
158 }
159}
160