Add context method to Error

This commit is contained in:
David Tolnay 2019-10-05 17:27:29 -04:00
parent b702096f5c
commit 41fde4cf29
No known key found for this signature in database
GPG Key ID: F9BA143B95FF6D82
2 changed files with 20 additions and 13 deletions

View File

@ -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>

View File

@ -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