diff options
Diffstat (limited to 'src/errors.rs')
| -rw-r--r-- | src/errors.rs | 88 |
1 files changed, 88 insertions, 0 deletions
diff --git a/src/errors.rs b/src/errors.rs new file mode 100644 index 0000000..251ee5f --- /dev/null +++ b/src/errors.rs @@ -0,0 +1,88 @@ +use axum::{ + http::StatusCode, + response::{IntoResponse, Response}, +}; +use derive_more::From; + +pub type Result<T> = core::result::Result<T, Error>; + +#[derive(Debug, From)] +pub enum Error { + ConfigNotFound, + ConfigHomeNotFound, + + #[from] + Io(std::io::Error), + + #[from] + EnvVar(std::env::VarError), + + #[from] + Askama(askama::Error), + + #[from] + SerdeError(serde_json::Error), + + #[from] + TomlDeError(toml::de::Error), + + #[from] + TomlSerError(toml::ser::Error), +} + +impl core::fmt::Display for Error { + fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::result::Result<(), std::fmt::Error> { + match self { + Error::ConfigNotFound => write!( + fmt, + "Config file can't be found at ~/.config/sbm-rs/config.toml" + ), + Error::ConfigHomeNotFound => write!(fmt, "Config home can't be found"), + Error::Io(e) => write!(fmt, "{e}"), + Error::EnvVar(e) => write!(fmt, "Environment variable error: {e}"), + Error::Askama(e) => write!(fmt, "Askama error: {e}"), + Error::SerdeError(e) => write!(fmt, "Serde error: {e}"), + Error::TomlDeError(e) => write!(fmt, "TOML deserialization error: {e}"), + Error::TomlSerError(e) => write!(fmt, "TOML serialization error: {e}"), + } + } +} + +impl IntoResponse for Error { + fn into_response(self) -> Response { + let (status, error_message) = match self { + Error::ConfigNotFound => ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Config file can't be found at ~/.config/sbm-rs/config.toml"), + ), + Error::ConfigHomeNotFound => ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Config home can't be found"), + ), + Error::Io(ref e) => (StatusCode::INTERNAL_SERVER_ERROR, format!("{e}")), + Error::EnvVar(ref e) => ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Environment variable error: {e}"), + ), + Error::Askama(ref e) => ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Askama error: {e}"), + ), + Error::SerdeError(ref e) => ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("Serde error: {e}"), + ), + Error::TomlDeError(ref e) => ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("TOML deserialization error: {e}"), + ), + Error::TomlSerError(ref e) => ( + StatusCode::INTERNAL_SERVER_ERROR, + format!("TOML serialization error: {e}"), + ), + }; + + println!("{} {}", &status, &error_message); + (status, error_message).into_response() + } +} |
