Skip to content
Myr

Document bail macro with examples

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Tolnay · committed by David Tolnay · parent 511886e · Browse files · 1 file+58 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

1 file+58 added−0 removed

  • other:+58 added−0 removed

1 file+58 added−0 removed

modified:src/lib.rs+58 added
217 unmodified lines
218219/// Return early with an error.220///221/// This macro is equivalent to `return Err(From::from($err))`.222///223/// # Example224///225/// ```226/// # use anyhow::{bail, Result};227/// #228/// # fn has_permission(user: usize, resource: usize) -> bool {229/// # true230/// # }231/// #232/// # fn main() -> Result<()> {233/// # let user = 0;234/// # let resource = 0;235/// #236/// if !has_permission(user, resource) {237/// bail!("permission denied for accessing {}", resource);238/// }239/// # Ok(())240/// # }241/// ```242///243/// ```244/// # use anyhow::{bail, Result};245/// # use std::fmt::{self, Display};246/// #247/// # #[derive(Debug)]248/// # enum ScienceError {249/// # RecursionLimitExceeded,250/// # }251/// #252/// # impl std::error::Error for ScienceError {}253/// #254/// # impl Display for ScienceError {255/// # fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {256/// # unimplemented!()257/// # }258/// # }259/// #260/// # const MAX_DEPTH: usize = 1;261/// #262/// # const IGNORE: &str = stringify! {263/// #[derive(Error, Debug)]264/// enum ScienceError {265/// #[error(display = "recursion limit exceeded")]266/// RecursionLimitExceeded,267/// ...268/// }269/// # };270///271/// # fn main() -> Result<()> {272/// # let depth = 0;273/// #274/// if depth > MAX_DEPTH {275/// bail!(ScienceError::RecursionLimitExceeded);276/// }277/// # Ok(())278/// # }279/// ```280#[macro_export]281macro_rules! bail {282 ($err:expr $(,)?) => {283 return std::result::Result::Err(std::convert::From::from($err));
43 unmodified lines