WorkTimer/src/error.rs

45 lines
1.3 KiB
Rust

use std::fmt;
use colored::*;
#[derive(Debug)]
pub enum CliError {
Network(String),
Server(String),
Parse(String),
Other(String),
}
impl std::error::Error for CliError {}
impl fmt::Display for CliError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let (label, message) = match self {
CliError::Network(msg) => ("Network Error".red(), msg),
CliError::Server(msg) => ("Server Error".red(), msg),
CliError::Parse(msg) => ("Parse Error".red(), msg),
CliError::Other(msg) => ("Error".red(), msg),
};
write!(f, "{}: {}", label, message)
}
}
impl From<reqwest::Error> for CliError {
fn from(err: reqwest::Error) -> Self {
if err.is_connect() {
CliError::Network("Could not connect to server".to_string())
} else if err.is_timeout() {
CliError::Network("Connection timed out".to_string())
} else if err.is_status() {
CliError::Server(format!("Server returned error: {}", err.status().unwrap_or_default()))
} else {
CliError::Network(err.to_string())
}
}
}
impl From<serde_json::Error> for CliError {
fn from(err: serde_json::Error) -> Self {
CliError::Parse(format!("Failed to parse server response: {}", err))
}
}