From 1c52ee772c97218257e50709f8fdf3ccd34d9962 Mon Sep 17 00:00:00 2001 From: Bugen Zhao Date: Wed, 7 Feb 2024 11:19:33 +0800 Subject: [PATCH] impl `Context` trait and `into_inner` Signed-off-by: Bugen Zhao --- src/error/src/anyhow.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/src/error/src/anyhow.rs b/src/error/src/anyhow.rs index 6f3dbc9c4765..e765d4194f23 100644 --- a/src/error/src/anyhow.rs +++ b/src/error/src/anyhow.rs @@ -51,6 +51,13 @@ macro_rules! def_anyhow_newtype { ($(#[$attr:meta])* $vis:vis $name:ident $(;)?) => { $(#[$attr])* $vis struct $name(::anyhow::Error); + impl $name { + /// Unwrap the newtype to get the inner [`anyhow::Error`]. + pub fn into_inner(self) -> ::anyhow::Error { + self.0 + } + } + impl std::ops::Deref for $name { type Target = ::anyhow::Error; @@ -85,5 +92,32 @@ macro_rules! def_anyhow_newtype { value.0.into() } } + + paste::paste! { + /// Provides the `context` method for `Result` of [`ConnectorError`]. + /// + /// This trait is the supplement of the [`anyhow::Context`] trait as it cannot be + /// implemented for types outside of the crate. + #[easy_ext::ext([< $name Context >])] + $vis impl Result { + /// Wrap the error value with additional context. + fn context(self, context: C) -> Result + where + C: std::fmt::Display + Send + Sync + 'static, + { + ::anyhow::Context::context(self.map_err(|error| error.0), context) + } + + /// Wrap the error value with additional context that is evaluated lazily + /// only once an error does occur. + fn with_context(self, context: F) -> Result + where + C: std::fmt::Display + Send + Sync + 'static, + F: FnOnce() -> C, + { + ::anyhow::Context::with_context(self.map_err(|error| error.0), context) + } + } + } }; }