You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
leanify-many/src/error.rs

69 lines
1.3 KiB

4 years ago
use std::{
error,
fmt,
};
#[derive(Debug)]
pub struct PrefixedError<T>
where T: error::Error + 'static
{
prefix: String,
internal: T,
}
impl<T> std::error::Error for PrefixedError<T>
where T: error::Error + 'static
{
fn source(&self) -> Option<&(dyn error::Error + 'static)>
{
Some(&self.internal)
}
}
impl<T> std::fmt::Display for PrefixedError<T>
where T: error::Error + 'static
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
write!(f, "{}: {}", self.prefix, self.internal)
}
}
impl<T> PrefixedError<T>
where T: error::Error + 'static
{
#[inline] pub fn into_inner(self) -> T
{
self.internal
}
}
pub trait ErrorExt: Sized + error::Error
{
fn with_prefix(self, msg: impl ToString) -> PrefixedError<Self>;
}
pub trait ResultExt<T,E>: Sized
where E: error::Error + 'static
{
fn with_prefix(self, msg: impl ToString) -> Result<T,PrefixedError<E>>;
}
impl<T> ErrorExt for T
where T: error::Error + 'static
{
#[inline] fn with_prefix(self, msg: impl ToString) -> PrefixedError<Self>
{
PrefixedError {
prefix: msg.to_string(),
internal: self
}
}
}
impl<T,E> ResultExt<T,E> for Result<T,E>
where E: error::Error + 'static
{
#[inline] fn with_prefix(self, msg: impl ToString) -> Result<T,PrefixedError<E>>
{
self.map_err(|e| e.with_prefix(msg))
}
}