use std::io;
use thiserror::Error;
#[derive(Error, Debug)]
pub enum LynnError {
#[error("IO error: {0}")]
Io(#[from] io::Error),
#[error("Network error: {0}")]
Network(String),
#[error("Connection error: {0}")]
Connection(String),
#[error("Invalid address: {0}")]
InvalidAddress(String),
#[error("Configuration error: {0}")]
Config(String),
#[error("Buffer error: {0}")]
Buffer(String),
#[error("Protocol error: {0}")]
Protocol(String),
#[error("Handler error: {0}")]
Handler(String),
#[error("Timeout: {0}")]
Timeout(String),
#[error("Client error: {0}")]
Client(String),
#[error("Server error: {0}")]
Server(String),
#[error("Error: {0}")]
Generic(String),
}
pub type Result<T> = std::result::Result<T, LynnError>;
impl LynnError {
pub fn network<S: Into<String>>(msg: S) -> Self {
Self::Network(msg.into())
}
pub fn connection<S: Into<String>>(msg: S) -> Self {
Self::Connection(msg.into())
}
pub fn invalid_address<S: Into<String>>(msg: S) -> Self {
Self::InvalidAddress(msg.into())
}
pub fn config<S: Into<String>>(msg: S) -> Self {
Self::Config(msg.into())
}
pub fn buffer<S: Into<String>>(msg: S) -> Self {
Self::Buffer(msg.into())
}
pub fn protocol<S: Into<String>>(msg: S) -> Self {
Self::Protocol(msg.into())
}
pub fn handler<S: Into<String>>(msg: S) -> Self {
Self::Handler(msg.into())
}
pub fn timeout<S: Into<String>>(msg: S) -> Self {
Self::Timeout(msg.into())
}
pub fn client<S: Into<String>>(msg: S) -> Self {
Self::Client(msg.into())
}
pub fn server<S: Into<String>>(msg: S) -> Self {
Self::Server(msg.into())
}
}
pub trait ToLynnError<T> {
fn with_context<S: Into<String>>(self, ctx: S) -> Result<T>;
}
impl<T, E> ToLynnError<T> for std::result::Result<T, E>
where
E: std::error::Error + Send + Sync + 'static,
{
fn with_context<S: Into<String>>(self, ctx: S) -> Result<T> {
self.map_err(|e| LynnError::Generic(format!("{}: {}", ctx.into(), e)))
}
}