Skip to content

Commit

Permalink
Merge pull request project-chip#93 from ssnover/std-box-dyn-error
Browse files Browse the repository at this point in the history
Add a boxed dyn error to make error info easier to access on hosted systems
  • Loading branch information
kedars authored Sep 25, 2023
2 parents 7ef08ad + c443a72 commit 0fe4ae9
Showing 1 changed file with 46 additions and 3 deletions.
49 changes: 46 additions & 3 deletions rs-matter/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ pub struct Error {
code: ErrorCode,
#[cfg(all(feature = "std", feature = "backtrace"))]
backtrace: std::backtrace::Backtrace,
#[cfg(all(feature = "std", feature = "backtrace"))]
inner: Option<Box<dyn std::error::Error + Send>>,
}

impl Error {
Expand All @@ -93,6 +95,22 @@ impl Error {
code,
#[cfg(all(feature = "std", feature = "backtrace"))]
backtrace: std::backtrace::Backtrace::capture(),
#[cfg(all(feature = "std", feature = "backtrace"))]
inner: None,
}
}

#[cfg(all(feature = "std", feature = "backtrace"))]
pub fn new_with_details(
code: ErrorCode,
detailed_err: Box<dyn std::error::Error + Send>,
) -> Self {
Self {
code,
#[cfg(all(feature = "std", feature = "backtrace"))]
backtrace: std::backtrace::Backtrace::capture(),
#[cfg(all(feature = "std", feature = "backtrace"))]
inner: Some(detailed_err),
}
}

Expand All @@ -105,6 +123,11 @@ impl Error {
&self.backtrace
}

#[cfg(all(feature = "std", feature = "backtrace"))]
pub fn details(&self) -> Option<&(dyn std::error::Error + Send)> {
self.inner.as_ref().map(|err| err.as_ref())
}

pub fn remap<F>(self, matcher: F, to: Self) -> Self
where
F: FnOnce(&Self) -> bool,
Expand Down Expand Up @@ -136,10 +159,16 @@ impl Error {
}
}

#[cfg(feature = "std")]
#[cfg(all(feature = "std", feature = "backtrace"))]
impl From<std::io::Error> for Error {
fn from(e: std::io::Error) -> Self {
Self::new_with_details(ErrorCode::StdIoError, Box::new(e))
}
}

#[cfg(all(feature = "std", not(feature = "backtrace")))]
impl From<std::io::Error> for Error {
fn from(_e: std::io::Error) -> Self {
// Keep things simple for now
Self::new(ErrorCode::StdIoError)
}
}
Expand Down Expand Up @@ -221,7 +250,21 @@ impl fmt::Debug for Error {

impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}", self.code())
#[cfg(all(feature = "std", feature = "backtrace"))]
{
write!(
f,
"{:?}: {}",
self.code(),
self.inner
.as_ref()
.map_or(String::new(), |err| { err.to_string() })
)
}
#[cfg(not(all(feature = "std", feature = "backtrace")))]
{
write!(f, "{:?}", self.code())
}
}
}

Expand Down

0 comments on commit 0fe4ae9

Please sign in to comment.