error.rs
⎇
Raw
1use std::path::PathBuf;
2
3use axum::http::StatusCode;
4use axum::response::{IntoResponse, Response};
5
6use crate::db::Db;
7
8#[derive(Clone)]
9pub struct AppState {
10 pub db: Db,
11 /// Canonicalized server root folder.
12 pub root: PathBuf,
13 /// Whether we sit behind a TLS-terminating reverse proxy.
14 pub https: bool,
15}
16
17/// API error. `extra` is optionally merged into the JSON body (e.g. a list of
18/// conflicting file names on a 409).
19#[derive(Debug, thiserror::Error)]
20#[error("{1}")]
21pub struct ApiError(pub StatusCode, pub String, pub Option<serde_json::Value>);
22
23impl ApiError {
24 pub fn new(status: StatusCode, msg: impl Into<String>) -> Self {
25 Self(status, msg.into(), None)
26 }
27
28 pub fn with_extra(mut self, extra: serde_json::Value) -> Self {
29 self.2 = Some(extra);
30 self
31 }
32}
33
34impl IntoResponse for ApiError {
35 fn into_response(self) -> Response {
36 let mut body = serde_json::json!({ "error": self.1 });
37 if let Some(extra) = self.2 {
38 if let (Some(obj), Some(extra)) = (body.as_object_mut(), extra.as_object()) {
39 for (k, v) in extra {
40 obj.insert(k.clone(), v.clone());
41 }
42 }
43 }
44 (self.0, axum::Json(body)).into_response()
45 }
46}
47
48impl From<std::io::Error> for ApiError {
49 fn from(e: std::io::Error) -> Self {
50 tracing::error!(error = %e, "io error");
51 ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal error")
52 }
53}
54
55impl From<rusqlite::Error> for ApiError {
56 fn from(e: rusqlite::Error) -> Self {
57 tracing::error!(error = %e, "database error");
58 ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal error")
59 }
60}
61