diff --git a/src/auth.rs b/src/auth.rs index 7fafebc..7d5d1e5 100644 --- a/src/auth.rs +++ b/src/auth.rs @@ -2,8 +2,11 @@ use std::sync::Arc; use serde::Deserialize; +use crate::{ErrorContext, logger}; use crate::{Server, utils::client::Client}; +logger!(LOGGER "Auth"); + #[derive(Debug, Deserialize)] struct AuthApiRes { user_id: u32, @@ -13,8 +16,10 @@ pub fn auth(_server: &Arc, client: &mut Client, token: &str) -> crate::R let mut res = ureq::get(format!( "http://localhost:3000/api/auth?intents=server&token={token}" )) - .call()?; + .call() + .context("Failed to authenticate")?; let api_res: AuthApiRes = serde_json::from_str(&res.body_mut().read_to_string()?)?; client.set_uuid(api_res.user_id); + LOGGER.info(format!("{} successfully authenticated", api_res.user_id)); Ok(api_res.user_id) } diff --git a/src/lib.rs b/src/lib.rs index f234a68..a55797e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -11,6 +11,7 @@ pub mod requests; pub mod types; pub mod utils; +pub use anyhow::Context as ErrorContext; pub use anyhow::Result; use crate::{utils::client::Client, utils::plugin::DynPlugin}; @@ -89,10 +90,18 @@ impl Server { Ok(stream) => { std::thread::spawn({ let srv = self.clone(); - let client = srv.init_client(stream)?; - move || match srv.wrap_err(&client, srv.handle_client(&client)) { - Ok(_) => {} - Err(e) => Self::LOGGER.error(format!("Client handler failed: {e}")), + + move || { + let Some(client) = Self::LOGGER + .extract(srv.init_client(stream), "Failed to initialize client") + else { + return; + }; + + Self::LOGGER.extract( + srv.wrap_err(&client, srv.handle_client(&client)), + "Client handler failed", + ); } }); } diff --git a/src/utils/logger.rs b/src/utils/logger.rs index ce1c849..6c6d52c 100644 --- a/src/utils/logger.rs +++ b/src/utils/logger.rs @@ -22,4 +22,24 @@ impl Logger { pub fn error(&self, message: T) { println!("\x1b[31mERROR\x1b[0m ({}) › {}", self.name, message); } + + pub fn extract(&self, v: Result, m: D) -> Option { + match v { + Ok(a) => Some(a), + Err(e) => { + self.error(format!("{m}: {e}")); + None + } + } + } + + pub fn extract_panic(&self, v: Result, m: D) -> T { + match v { + Ok(a) => a, + Err(e) => { + self.error(format!("{m}: {e}")); + panic!() + } + } + } }