From 52e4abb1f2167c71c2f99d9a1048d9321baed963 Mon Sep 17 00:00:00 2001 From: David Tolnay Date: Sun, 22 Dec 2024 03:19:46 -0800 Subject: [PATCH] Add Error::from_boxed with documentation about bidirectional `?` --- src/error.rs | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) diff --git a/src/error.rs b/src/error.rs index 76369a9..cd1f5f5 100644 --- a/src/error.rs +++ b/src/error.rs @@ -85,6 +85,67 @@ impl Error { Error::construct_from_adhoc(message, backtrace!()) } + /// Construct an error object from a type-erased standard library error. + /// + /// This is mostly useful for interop with other error libraries. + /// + /// # Example + /// + /// Here is a skeleton of a library that provides its own error abstraction. + /// The pair of `From` impls provide bidirectional support for `?` + /// conversion between `Report` and `anyhow::Error`. + /// + /// ``` + /// use std::error::Error as StdError; + /// + /// pub struct Report {/* ... */} + /// + /// impl From for Report + /// where + /// E: Into, + /// Result<(), E>: anyhow::Context<(), E>, + /// { + /// fn from(error: E) -> Self { + /// let anyhow_error: anyhow::Error = error.into(); + /// let boxed_error: Box = anyhow_error.into(); + /// Report::from_boxed(boxed_error) + /// } + /// } + /// + /// impl From for anyhow::Error { + /// fn from(report: Report) -> Self { + /// let boxed_error: Box = report.into_boxed(); + /// anyhow::Error::from_boxed(boxed_error) + /// } + /// } + /// + /// impl Report { + /// fn from_boxed(boxed_error: Box) -> Self { + /// todo!() + /// } + /// fn into_boxed(self) -> Box { + /// todo!() + /// } + /// } + /// + /// // Example usage: can use `?` in both directions. + /// fn a() -> anyhow::Result<()> { + /// b()?; + /// Ok(()) + /// } + /// fn b() -> Result<(), Report> { + /// a()?; + /// Ok(()) + /// } + /// ``` + #[cfg(any(feature = "std", not(anyhow_no_core_error)))] + #[cold] + #[must_use] + pub fn from_boxed(boxed_error: Box) -> Self { + let backtrace = backtrace_if_absent!(&*boxed_error); + Error::construct_from_boxed(boxed_error, backtrace) + } + #[cfg(any(feature = "std", not(anyhow_no_core_error)))] #[cold] pub(crate) fn construct_from_std(error: E, backtrace: Option) -> Self