From e771639856d461ceab26aaeda4cab69f6bc1d81c Mon Sep 17 00:00:00 2001 From: mirsal Date: Thu, 15 May 2025 19:09:41 +0000 Subject: [PATCH] config: Rework error handling into explicit error types --- src/config.rs | 28 +++++++++++++++++++++++----- src/main.rs | 6 ++++-- 2 files changed, 27 insertions(+), 7 deletions(-) diff --git a/src/config.rs b/src/config.rs index 1e9356f..69862fd 100644 --- a/src/config.rs +++ b/src/config.rs @@ -18,8 +18,16 @@ */ use serde::Deserialize; -use std::error::Error; -use std::fs; +use std::{fs, io}; + +#[derive(Debug)] +#[allow(dead_code)] +pub enum Error { + FileNotFoundError(String), + PermissionDeniedError(), + InvalidFormatError(serde_yaml::Error), + IoError(io::Error), +} #[derive(Deserialize, Clone, Debug)] pub struct FeedConfig { @@ -38,9 +46,19 @@ pub struct Config { } impl Config { - pub fn load(config_file: &str) -> Result> { - let serialized_config = fs::read_to_string(config_file)?; - let config: Config = serde_yaml::from_str(&serialized_config)?; + pub fn load(config_file: &str) -> Result { + + let serialized_config = fs::read_to_string(config_file).map_err(|e| { + match e.kind() { + io::ErrorKind::NotFound => Error::FileNotFoundError(config_file.into()), + io::ErrorKind::PermissionDenied => Error::PermissionDeniedError(), + _ => Error::IoError(e), + } + })?; + + let config: Config = serde_yaml::from_str(&serialized_config) + .map_err(|e| Error::InvalidFormatError(e))?; + Ok(config) } } diff --git a/src/main.rs b/src/main.rs index ba42f92..0bffc6c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -46,7 +46,9 @@ use chrono::DateTime; async fn main() -> anyhow::Result<()> { tracing_subscriber::fmt::init(); - let config = Config::load("bots.yaml").expect("Failed to load config"); + let config = Config::load("bots.yaml").unwrap_or_else(|e| { + panic!("Failed to load config: {e:?}") + }); let config = Arc::new(config); // This message passing channel is used for sending messages to the matrix module, @@ -109,7 +111,7 @@ async fn main() -> anyhow::Result<()> { if parsed.ts > state_ts { info!("Entry {} has not been posted yet, sending to matrix", entry.id); - let msg = parsed.formatted.unwrap(); + let msg = parsed.formatted.unwrap(); // XXX bcast_tx.send((msg, rooms.clone())).unwrap(); max_ts = max(max_ts, parsed.ts);