mirror of
https://github.com/eyre-rs/eyre.git
synced 2025-09-27 13:01:29 +00:00
Add context method to Error
This commit is contained in:
parent
b702096f5c
commit
41fde4cf29
@ -29,7 +29,7 @@ where
|
||||
self.map_err(|error| Error::from(ContextError { error, context }))
|
||||
}
|
||||
|
||||
fn with_context<C, F>(self, f: F) -> Result<T, Error>
|
||||
fn with_context<C, F>(self, context: F) -> Result<T, Error>
|
||||
where
|
||||
C: Display + Send + Sync + 'static,
|
||||
F: FnOnce() -> C,
|
||||
@ -37,7 +37,7 @@ where
|
||||
self.map_err(|error| {
|
||||
Error::from(ContextError {
|
||||
error,
|
||||
context: f(),
|
||||
context: context(),
|
||||
})
|
||||
})
|
||||
}
|
||||
@ -48,26 +48,21 @@ impl<T> Context<T, Error> for Result<T, Error> {
|
||||
where
|
||||
C: Display + Send + Sync + 'static,
|
||||
{
|
||||
self.map_err(|error| Error::from(ContextError { error, context }))
|
||||
self.map_err(|error| error.context(context))
|
||||
}
|
||||
|
||||
fn with_context<C, F>(self, f: F) -> Result<T, Error>
|
||||
fn with_context<C, F>(self, context: F) -> Result<T, Error>
|
||||
where
|
||||
C: Display + Send + Sync + 'static,
|
||||
F: FnOnce() -> C,
|
||||
{
|
||||
self.map_err(|error| {
|
||||
Error::from(ContextError {
|
||||
error,
|
||||
context: f(),
|
||||
})
|
||||
})
|
||||
self.map_err(|error| error.context(context()))
|
||||
}
|
||||
}
|
||||
|
||||
struct ContextError<E, C> {
|
||||
error: E,
|
||||
context: C,
|
||||
pub(crate) struct ContextError<E, C> {
|
||||
pub error: E,
|
||||
pub context: C,
|
||||
}
|
||||
|
||||
impl<E, C> Debug for ContextError<E, C>
|
||||
|
12
src/error.rs
12
src/error.rs
@ -1,3 +1,4 @@
|
||||
use crate::context::ContextError;
|
||||
use std::any::TypeId;
|
||||
use std::backtrace::{Backtrace, BacktraceStatus};
|
||||
use std::error::Error as StdError;
|
||||
@ -66,6 +67,17 @@ impl Error {
|
||||
}
|
||||
}
|
||||
|
||||
/// Wrap the error value with additional context.
|
||||
pub fn context<C>(self, context: C) -> Self
|
||||
where
|
||||
C: Display + Send + Sync + 'static,
|
||||
{
|
||||
Error::from(ContextError {
|
||||
error: self,
|
||||
context,
|
||||
})
|
||||
}
|
||||
|
||||
/// View this error object as the underlying error.
|
||||
pub fn as_dyn_error(&self) -> &(dyn StdError + Send + Sync + 'static) {
|
||||
&**self
|
||||
|
Loading…
x
Reference in New Issue
Block a user