error.rs
| 1 | use std::path::PathBuf; |
| 2 | |
| 3 | use axum::http::StatusCode; |
| 4 | use axum::response::{IntoResponse, Response}; |
| 5 | |
| 6 | use crate::db::Db; |
| 7 | |
| 8 | #[derive(Clone)] |
| 9 | pub 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 | #[derive(Debug, thiserror::Error)] |
| 18 | #[error("{1}")] |
| 19 | pub struct ApiError(pub StatusCode, pub String); |
| 20 | |
| 21 | impl ApiError { |
| 22 | pub fn new(status: StatusCode, msg: impl Into<String>) -> Self { |
| 23 | Self(status, msg.into()) |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | impl IntoResponse for ApiError { |
| 28 | fn into_response(self) -> Response { |
| 29 | ( |
| 30 | self.0, |
| 31 | axum::Json(serde_json::json!({ "error": self.1 })), |
| 32 | ) |
| 33 | .into_response() |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | impl From<rusqlite::Error> for ApiError { |
| 38 | fn from(e: rusqlite::Error) -> Self { |
| 39 | tracing::error!(error = %e, "database error"); |
| 40 | ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal error") |
| 41 | } |
| 42 | } |
| 43 |