From 0449580b9b65c96f9042724fc805c35bb881abe9 Mon Sep 17 00:00:00 2001 From: Erwin Boskma Date: Fri, 14 Jan 2022 10:13:02 +0100 Subject: [PATCH] Improve error handling --- src/main.rs | 40 ++++++++++++++++++++++------------------ 1 file changed, 22 insertions(+), 18 deletions(-) diff --git a/src/main.rs b/src/main.rs index 7717481..69223a4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,9 +1,11 @@ -use std::{io::Read, path::PathBuf}; +use std::io::Read; +use std::path::PathBuf; use clap::Parser; -use color_eyre::Report; +use color_eyre::{eyre::WrapErr, Result}; use serde_json::json; -use tracing::{debug, error}; +use std::fmt::Display; +use tracing::debug; use tracing_subscriber::EnvFilter; /// Bert @@ -46,13 +48,18 @@ enum Command { /// Lower volume VolumeDown, } -fn main() { - if let Err(e) = do_main() { - error!("Fatal error: {}", e); + +impl Display for Command { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Command::PlayPause => write!(f, "Play/Pause"), + Command::VolumeUp => write!(f, "Volume Up"), + Command::VolumeDown => write!(f, "Volume Down"), + } } } -fn do_main() -> Result<(), Box> { +fn main() -> Result<()> { let opts = Opts::parse(); let Opts { @@ -65,7 +72,7 @@ fn do_main() -> Result<(), Box> { token_file, } = opts; - setup(debug)?; + setup(debug).wrap_err("Setup failed")?; let token = if let Some(token) = token { Some(token) @@ -84,16 +91,18 @@ fn do_main() -> Result<(), Box> { if let Some(token) = token { if let Some(cmd) = cmd { - call_service(cmd, host, entity, insecure, token)?; + call_service(cmd, host, entity, insecure, token) + .wrap_err_with(|| format!("Unable to execute command {cmd}"))?; } else { - get_now_playing(host, entity, insecure, token)?; + get_now_playing(host, entity, insecure, token) + .wrap_err("Unable to retrieve now playing info")?; } } // println!("{:#?}", response); Ok(()) } -fn setup(debug: bool) -> Result<(), Report> { +fn setup(debug: bool) -> Result<()> { if debug { std::env::set_var("RUST_LOG", "debug"); } @@ -106,12 +115,7 @@ fn setup(debug: bool) -> Result<(), Report> { Ok(()) } -fn get_now_playing( - host: String, - entity: String, - insecure: bool, - token: String, -) -> Result<(), Box> { +fn get_now_playing(host: String, entity: String, insecure: bool, token: String) -> Result<()> { let url = format!( "{}://{}/api/states/{}", if insecure { "http" } else { "https" }, @@ -174,7 +178,7 @@ fn call_service( entity: String, insecure: bool, token: String, -) -> Result<(), Box> { +) -> Result<()> { let cmd = match command { Command::PlayPause => "media_play_pause", Command::VolumeUp => "volume_up",