use thiserror::Error;
#[derive(Error, Debug)]
pub enum BombError {
#[error("Configuration error: {0}")]
Config(String),
#[error("Transport error: {0}")]
Transport(String),
#[error("Test execution error: {0}")]
TestExecution(String),
#[error("Message error: {0}")]
Message(String),
#[error("URL parse error: {0}")]
UrlParse(#[from] url::ParseError),
#[error("HTTP request error: {0}")]
HttpRequest(#[from] reqwest::Error),
#[error("JSON serialization error: {0}")]
JsonSerialization(#[from] serde_json::Error),
#[error("WebSocket error: {0}")]
WebSocket(Box<tokio_tungstenite::tungstenite::Error>),
}
pub type Result<T> = std::result::Result<T, BombError>;
pub trait ErrorContext<T> {
fn with_config_context(self, msg: &str) -> Result<T>;
fn with_transport_context(self, msg: &str) -> Result<T>;
fn with_message_context(self, msg: &str) -> Result<T>;
}
impl<T, E> ErrorContext<T> for std::result::Result<T, E>
where
E: std::fmt::Display,
{
fn with_config_context(self, msg: &str) -> Result<T> {
self.map_err(|e| BombError::Config(format!("{}: {}", msg, e)))
}
fn with_transport_context(self, msg: &str) -> Result<T> {
self.map_err(|e| BombError::Transport(format!("{}: {}", msg, e)))
}
fn with_message_context(self, msg: &str) -> Result<T> {
self.map_err(|e| BombError::Message(format!("{}: {}", msg, e)))
}
}
impl<T> ErrorContext<T> for Option<T> {
fn with_config_context(self, msg: &str) -> Result<T> {
self.ok_or_else(|| BombError::Config(msg.to_string()))
}
fn with_transport_context(self, msg: &str) -> Result<T> {
self.ok_or_else(|| BombError::Transport(msg.to_string()))
}
fn with_message_context(self, msg: &str) -> Result<T> {
self.ok_or_else(|| BombError::Message(msg.to_string()))
}
}
impl BombError {
pub fn config<S: Into<String>>(msg: S) -> Self {
BombError::Config(msg.into())
}
pub fn execution<S: Into<String>>(msg: S) -> Self {
BombError::TestExecution(msg.into())
}
}
impl From<tokio_tungstenite::tungstenite::Error> for BombError {
fn from(err: tokio_tungstenite::tungstenite::Error) -> Self {
BombError::WebSocket(Box::new(err))
}
}