From 320e41c6f279f6e0cab1e414d5296df6b27e6410 Mon Sep 17 00:00:00 2001 From: Edward Shen Date: Sat, 21 Dec 2019 15:56:59 -0500 Subject: [PATCH] graceful bad-config handling --- src/main.rs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/main.rs b/src/main.rs index 7daea2d..85267df 100644 --- a/src/main.rs +++ b/src/main.rs @@ -21,12 +21,14 @@ static CONFIG_FILE: &str = "bunbun.toml"; #[derive(Debug)] enum BunBunError { IoError(std::io::Error), + ParseError(serde_yaml::Error), } impl fmt::Display for BunBunError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { BunBunError::IoError(e) => e.fmt(f), + BunBunError::ParseError(e) => e.fmt(f), } } } @@ -39,6 +41,12 @@ impl From for BunBunError { } } +impl From for BunBunError { + fn from(error: serde_yaml::Error) -> Self { + BunBunError::ParseError(error) + } +} + #[get("/ls")] fn list(data: Data>>) -> impl Responder { let data = data.read().unwrap(); @@ -162,10 +170,14 @@ fn main() -> Result<(), BunBunError> { .watch(CONFIG_FILE, move |e: Event| { if let Event::Write(_) = e { let mut state = state.write().unwrap(); - let conf = read_config(CONFIG_FILE).unwrap(); - state.public_address = conf.public_address; - state.default_route = conf.default_route; - state.routes = conf.routes; + match read_config(CONFIG_FILE) { + Ok(conf) => { + state.public_address = conf.public_address; + state.default_route = conf.default_route; + state.routes = conf.routes; + } + Err(e) => eprintln!("Config is malformed: {}", e), + } } }) .expect("failed to watch"); @@ -201,8 +213,7 @@ fn read_config(config_file_path: &str) -> Result { File::open(config_file_path)? } }; - // TODO: Handle parse failure - Ok(serde_yaml::from_reader(config_file).unwrap()) + Ok(serde_yaml::from_reader(config_file)?) } fn compile_templates() -> Handlebars {