use std::{
borrow::Cow,
fmt::Display,
sync::{MutexGuard, PoisonError, RwLockReadGuard, RwLockWriteGuard},
};
pub type Result<T, E = Error> = std::result::Result<T, E>;
pub type AnyError = Box<dyn std::error::Error>;
pub type AnyResult<T> = std::result::Result<T, AnyError>;
#[derive(thiserror::Error, Debug, Clone)]
pub enum Error {
#[error("Decoding error: {0}")]
Decode(String),
#[error("RwLock read error: {0}")]
RwLockReadError(String),
#[error("RwLock write error: {0}")]
RwLockWriteError(String),
#[error("Mutex error: {0}")]
MutexError(String),
#[error("Mpsc Recv Error: {0}")]
RecvError(#[from] std::sync::mpsc::RecvError),
#[error("400 Bad Request")]
BadRequest,
#[error("Exists: {0}")]
Exists(Cow<'static, str>),
#[error("Str: {0}")]
Str(Cow<'static, str>),
#[error("String: {0}")]
String(String),
#[cfg(feature = "regex")]
#[error("regex error: {0}")]
Regex(#[from] regex::Error),
#[error("authentication required: {0}")]
Unauthorized(&'static str),
#[error("user may not perform that action")]
Forbidden,
#[error("request path not found: {0}")]
NotFound(Cow<'static, str>),
#[error("Option<{0}>")]
Option(Cow<'static, str>),
#[error("Not supported: {0}")]
Unsupport(Cow<'static, str>),
#[error("TryFromSlice: {0}")]
TryFromSlice(#[from] std::array::TryFromSliceError),
#[error("env var error : {0}")]
Env(#[from] std::env::VarError),
#[error("Empty")]
Empty,
#[error("an error occurred with the parse Error: {0}")]
ParseNumber(#[from] std::num::ParseIntError),
#[error("an error occurred with the parse Error: {0}")]
ParseFloatError(#[from] std::num::ParseFloatError),
#[error("Log: {0}")]
Log(Cow<'static, str>),
#[error("CString: {0}")]
Nul(#[from] std::ffi::NulError),
#[error("{0}")]
Any(String),
}
impl From<String> for Error {
fn from(s: String) -> Self {
Error::String(s)
}
}
impl From<&'static str> for Error {
fn from(s: &'static str) -> Self {
Error::Str(Cow::Borrowed(s))
}
}
impl<T: Send + Sync + 'static> From<PoisonError<RwLockReadGuard<'_, T>>> for Error {
fn from(err: PoisonError<RwLockReadGuard<'_, T>>) -> Self {
Error::RwLockReadError(err.to_string())
}
}
impl<T: Send + Sync + 'static> From<PoisonError<MutexGuard<'_, T>>> for Error {
fn from(err: PoisonError<MutexGuard<'_, T>>) -> Self {
Error::MutexError(err.to_string())
}
}
impl<T: Send + Sync + 'static> From<PoisonError<RwLockWriteGuard<'_, T>>> for Error {
fn from(err: PoisonError<RwLockWriteGuard<'_, T>>) -> Self {
Error::RwLockWriteError(err.to_string())
}
}
pub trait AnyRes<T, E> {
fn any(self) -> Result<T>;
}
impl<T, E: Display> AnyRes<T, E> for std::result::Result<T, E> {
fn any(self) -> Result<T> {
match self {
Ok(v) => Result::Ok(v),
Err(e) => Result::Err(Error::Any(e.to_string())),
}
}
}