Skip to main content

claviron_cache/
error.rs

1#[cfg(feature = "axum")]
2use axum::response::{IntoResponse, Response};
3#[cfg(feature = "axum")]
4use serde_json::json;
5
6pub type Result<T> = std::result::Result<T, Error>;
7
8#[derive(thiserror::Error, Debug)]
9pub enum Error {
10    #[error("cache io error: {0}")]
11    Io(#[from] std::io::Error),
12
13    #[error("cache config parse error: {0}")]
14    Yaml(#[from] serde_yaml::Error),
15
16    #[cfg(feature = "redis")]
17    #[error("cache redis error: {0}")]
18    Redis(#[from] redis::RedisError),
19
20    #[error("cache file storage error: {0}")]
21    Storage(#[from] cacache::Error),
22
23    #[error("cache missing: {0}")]
24    Missing(String),
25
26    #[error("cache rejected: {0}")]
27    Rejected(String),
28
29    #[error("cache other: {0}")]
30    Other(String),
31}
32
33impl Error {
34    pub fn other(err: impl std::fmt::Display) -> Self {
35        Self::Other(err.to_string())
36    }
37
38    pub fn wrap(
39        msg: impl std::fmt::Display,
40        err: impl std::fmt::Display,
41    ) -> Self {
42        Self::Other(format!("{msg}: {err}"))
43    }
44}
45
46impl From<String> for Error {
47    fn from(value: String) -> Self {
48        Self::Other(value)
49    }
50}
51
52impl From<&str> for Error {
53    fn from(value: &str) -> Self {
54        Self::Other(value.to_string())
55    }
56}
57
58#[cfg(feature = "orbit")]
59impl From<claviron_orbit::cache::Error> for Error {
60    fn from(value: claviron_orbit::cache::Error) -> Self {
61        Self::wrap("Orbit cache operation failed", value)
62    }
63}
64
65impl From<crate::ValueError> for Error {
66    fn from(value: crate::ValueError) -> Self {
67        Self::wrap("cache value operation failed", value)
68    }
69}
70
71#[cfg(feature = "axum")]
72impl IntoResponse for Error {
73    fn into_response(self) -> Response {
74        let (status, body) = match self {
75            Error::Missing(message) => {
76                (axum::http::StatusCode::NOT_FOUND, json!({ "error": message }))
77            }
78            Error::Rejected(message) => (
79                axum::http::StatusCode::NOT_IMPLEMENTED,
80                json!({ "error": message }),
81            ),
82            other => (
83                axum::http::StatusCode::INTERNAL_SERVER_ERROR,
84                json!({ "error": other.to_string() }),
85            ),
86        };
87
88        (status, body.to_string()).into_response()
89    }
90}