Improve error handling

This commit is contained in:
Erwin Boskma 2022-01-14 10:13:02 +01:00
parent d296105443
commit 0449580b9b
Signed by: erwin
GPG key ID: 270B20D17394F7E5

View file

@ -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<dyn std::error::Error>> {
fn main() -> Result<()> {
let opts = Opts::parse();
let Opts {
@ -65,7 +72,7 @@ fn do_main() -> Result<(), Box<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
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<dyn std::error::Error>> {
) -> Result<()> {
let cmd = match command {
Command::PlayPause => "media_play_pause",
Command::VolumeUp => "volume_up",