Skip to content
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

Add Error::from_boxed with documentation about bidirectional ? #402

Merged
merged 1 commit into from
Dec 22, 2024
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
61 changes: 61 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<E> From<E> for Report
/// where
/// E: Into<anyhow::Error>,
/// Result<(), E>: anyhow::Context<(), E>,
/// {
/// fn from(error: E) -> Self {
/// let anyhow_error: anyhow::Error = error.into();
/// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = anyhow_error.into();
/// Report::from_boxed(boxed_error)
/// }
/// }
///
/// impl From<Report> for anyhow::Error {
/// fn from(report: Report) -> Self {
/// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = report.into_boxed();
/// anyhow::Error::from_boxed(boxed_error)
/// }
/// }
///
/// impl Report {
/// fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {
/// todo!()
/// }
/// fn into_boxed(self) -> Box<dyn StdError + Send + Sync + 'static> {
/// 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<dyn StdError + Send + Sync + 'static>) -> 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<E>(error: E, backtrace: Option<Backtrace>) -> Self
Expand Down
Loading