Improve error handling for events and in general

This commit is contained in:
Tobias Reisinger 2024-03-27 15:37:52 +01:00
parent 8d1e813c0b
commit f860fe3689
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
6 changed files with 114 additions and 104 deletions

View file

@ -1,4 +1,3 @@
use std::process::exit;
use std::time::Duration;
use telnet::Event::TimedOut;
@ -11,34 +10,28 @@ use crate::models::Client;
use crate::response::Response;
use crate::utils::SendTextMessageTarget;
pub fn skip_welcome(connection: &mut Telnet) {
pub fn skip_welcome(connection: &mut Telnet) -> Result<(), String> {
loop {
let event_result = connection.read_timeout(Duration::from_millis(100));
match event_result {
Ok(event) => {
if let TimedOut = event {
break;
return Ok(());
}
}
Err(_) => println!("Failed to read from Teamspeak."),
Err(_) => return Err(String::from("Failed to read from Teamspeak.")),
}
}
}
pub fn login(connection: &mut Telnet) {
pub fn login(connection: &mut Telnet) -> Result<(), String> {
// read api key from environment variable
let apikey = std::env::var("TS3_CLIENT_API_KEY").unwrap_or_else(|_| {
println!("No API key found in environment variable TS3_CLIENT_API_KEY.");
exit(1);
});
let apikey = std::env::var("TS3_CLIENT_API_KEY")
.map_err(|_| String::from("No API key found in environment variable TS3_CLIENT_API_KEY."))?;
match commands::login(connection, &apikey) {
Ok(_) => {}
Err(msg) => {
println!("Failed to authenticate with Teamspeak: {}", msg);
exit(1);
}
}
commands::login(connection, &apikey)
.map(|_| ())
.map_err(|err| format!("Failed to authenticate with Teamspeak: {}", err))
}
pub fn get_channels(connection: &mut Telnet, spacers: bool) -> Result<Vec<Channel>, String> {