mirror of
https://github.com/haraldh/chainerror.git
synced 2025-06-05 07:44:36 +02:00
feat: add annotate()
method to Context
to just annotate the passed error with location data Signed-off-by: Harald Hoyer <harald@hoyer.xyz>
This commit is contained in:
parent
101d2074e1
commit
46b7f58e72
2 changed files with 38 additions and 2 deletions
31
src/lib.rs
31
src/lib.rs
|
@ -216,6 +216,9 @@ pub trait Context<O, E: Into<Box<dyn StdError + 'static + Send + Sync>>> {
|
|||
/// Decorate the error with a `kind` of type `T` and the source `Location`
|
||||
fn context<T: 'static + Display + Debug>(self, kind: T) -> std::result::Result<O, Error<T>>;
|
||||
|
||||
/// Decorate the error just with the source `Location`
|
||||
fn annotate(self) -> std::result::Result<O, Error<AnnotatedError>>;
|
||||
|
||||
/// Decorate the `error` with a `kind` of type `T` produced with a `FnOnce(&error)` and the source `Location`
|
||||
fn map_context<T: 'static + Display + Debug, F: FnOnce(&E) -> T>(
|
||||
self,
|
||||
|
@ -223,6 +226,21 @@ pub trait Context<O, E: Into<Box<dyn StdError + 'static + Send + Sync>>> {
|
|||
) -> std::result::Result<O, Error<T>>;
|
||||
}
|
||||
|
||||
/// Convenience type to just decorate the error with the source `Location`
|
||||
pub struct AnnotatedError(());
|
||||
|
||||
impl Display for AnnotatedError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "(passed error)")
|
||||
}
|
||||
}
|
||||
|
||||
impl Debug for AnnotatedError {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "(passed error)")
|
||||
}
|
||||
}
|
||||
|
||||
impl<O, E: Into<Box<dyn StdError + 'static + Send + Sync>>> Context<O, E>
|
||||
for std::result::Result<O, E>
|
||||
{
|
||||
|
@ -239,6 +257,19 @@ impl<O, E: Into<Box<dyn StdError + 'static + Send + Sync>>> Context<O, E>
|
|||
}
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
#[inline]
|
||||
fn annotate(self) -> std::result::Result<O, Error<AnnotatedError>> {
|
||||
match self {
|
||||
Ok(t) => Ok(t),
|
||||
Err(error_cause) => Err(Error::new(
|
||||
AnnotatedError(()),
|
||||
Some(error_cause.into()),
|
||||
Some(Location::caller().to_string()),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[track_caller]
|
||||
#[inline]
|
||||
fn map_context<T: 'static + Display + Debug, F: FnOnce(&E) -> T>(
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue