use thiserror::Error;
#[derive(Error, Debug)]
pub enum NanonisError {
#[error("IO error: {context}")]
Io {
#[source]
source: std::io::Error,
context: String,
},
#[error("Timeout{}", if .0.is_empty() { String::new() } else { format!(": {}", .0) })]
Timeout(String),
#[error("Protocol error: {0}")]
Protocol(String),
#[error("Server error: {message} (code: {code})")]
Server { code: i32, message: String },
}
impl NanonisError {
pub fn is_server_error(&self) -> bool {
matches!(self, NanonisError::Server { .. })
}
pub fn error_code(&self) -> Option<i32> {
match self {
NanonisError::Server { code, .. } => Some(*code),
_ => None,
}
}
pub fn is_timeout(&self) -> bool {
matches!(self, NanonisError::Timeout(_))
}
pub fn is_io(&self) -> bool {
matches!(self, NanonisError::Io { .. })
}
pub fn is_protocol(&self) -> bool {
matches!(self, NanonisError::Protocol(_))
}
}
impl From<std::io::Error> for NanonisError {
fn from(error: std::io::Error) -> Self {
NanonisError::Io {
source: error,
context: "IO operation failed".to_string(),
}
}
}
impl From<serde_json::Error> for NanonisError {
fn from(error: serde_json::Error) -> Self {
NanonisError::Protocol(format!("JSON serialization error: {error}"))
}
}