[−][src]Macro adhocerr::wrap
Thinly wrap an error by defining a hidden error type and returning a closure to construct it
Examples
Wrap an error without changing its size or allocating:
use adhocerr::wrap; fn record_success() -> Result<(), impl Error + 'static> { std::fs::write(".success", "true").map_err(wrap!("Failed to save results of script")) }
Which expands to:
fn record_success() -> Result<(), impl Error + 'static> { std::fs::write(".success", "true").map_err({ #[derive(Debug)] struct WrappedError<E> { source: E, } impl<E> std::error::Error for WrappedError<E> where E: std::error::Error + 'static, { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.source) } } impl<E> core::fmt::Display for WrappedError<E> where E: std::error::Error + 'static, { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.write_str("Failed to save results of script") } } |source| WrappedError { source } }) }
Wrapping an error with an runtime generated String:
use adhocerr::wrap; fn record_success(file: &Path) -> Result<(), impl Error + 'static> { std::fs::write(file, "true").map_err(wrap!( "Failed to save results of script to file: {}", file.display() )) }
Which expands to:
fn record_success(file: &Path) -> Result<(), impl Error + 'static> { std::fs::write(file, "true").map_err(|source| { adhocerr::private::format_wrap_err( source, format_args!( "Failed to save results of script to file: {}", file.display() ), ) }) }