Skip to content

Track type name on error before losing that info #213

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 12, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ pub type Result<T> = std::result::Result<T, Error>;
pub struct Error {
error: anyhow::Error,
status: crate::StatusCode,
type_name: Option<&'static str>,
}

impl Error {
Expand All @@ -24,16 +25,18 @@ impl Error {
/// The error type must be threadsafe and 'static, so that the Error will be
/// as well. If the error type does not provide a backtrace, a backtrace will
/// be created here to ensure that a backtrace exists.
pub fn new<S>(status: S, error: impl Into<anyhow::Error>) -> Self
pub fn new<S, E>(status: S, error: E) -> Self
where
S: TryInto<StatusCode>,
S::Error: Debug,
E: Into<anyhow::Error>,
{
Self {
status: status
.try_into()
.expect("Could not convert into a valid `StatusCode`"),
error: error.into(),
type_name: Some(std::any::type_name::<E>()),
}
}

Expand All @@ -49,6 +52,7 @@ impl Error {
.try_into()
.expect("Could not convert into a valid `StatusCode`"),
error: anyhow::Error::msg(msg),
type_name: None,
}
}
/// Create a new error from a message.
Expand Down Expand Up @@ -112,6 +116,11 @@ impl Error {
{
self.error.downcast_mut::<E>()
}

/// Retrieves a reference to the type name of the error, if available.
pub fn type_name(&self) -> Option<&str> {
self.type_name.as_deref()
}
}

impl Display for Error {
Expand Down