Skip to content
Myr

lib.rs

This file

Path

src/lib.rs

728 lines · 20.7 KiB · Rust

Last changed by

Release 1.0.104David Tolnaybefore adoption1dbe186

History of this file

Take it

1//! [![github]](https://github.com/dtolnay/anyhow)&ensp;[![crates-io]](https://crates.io/crates/anyhow)&ensp;[![docs-rs]](https://docs.rs/anyhow)2//!3//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust5//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs6//!7//! <br>8//!9//! This library provides [`anyhow::Error`][Error], a trait object based error10//! type for easy idiomatic error handling in Rust applications.11//!12//! <br>13//!14//! # Details15//!16//! - Use `Result<T, anyhow::Error>`, or equivalently `anyhow::Result<T>`, as17//!   the return type of any fallible function.18//!19//!   Within the function, use `?` to easily propagate any error that implements20//!   the [`std::error::Error`] trait.21//!22//!   ```23//!   # pub trait Deserialize {}24//!   #25//!   # mod serde_json {26//!   #     use super::Deserialize;27//!   #     use std::io;28//!   #29//!   #     pub fn from_str<T: Deserialize>(json: &str) -> io::Result<T> {30//!   #         unimplemented!()31//!   #     }32//!   # }33//!   #34//!   # struct ClusterMap;35//!   #36//!   # impl Deserialize for ClusterMap {}37//!   #38//!   use anyhow::Result;39//!40//!   fn get_cluster_info() -> Result<ClusterMap> {41//!       let config = std::fs::read_to_string("cluster.json")?;42//!       let map: ClusterMap = serde_json::from_str(&config)?;43//!       Ok(map)44//!   }45//!   #46//!   # fn main() {}47//!   ```48//!49//! - Attach context to help the person troubleshooting the error understand50//!   where things went wrong. A low-level error like "No such file or51//!   directory" can be annoying to debug without more context about what higher52//!   level step the application was in the middle of.53//!54//!   ```55//!   # struct It;56//!   #57//!   # impl It {58//!   #     fn detach(&self) -> Result<()> {59//!   #         unimplemented!()60//!   #     }61//!   # }62//!   #63//!   use anyhow::{Context, Result};64//!65//!   fn main() -> Result<()> {66//!       # return Ok(());67//!       #68//!       # const _: &str = stringify! {69//!       ...70//!       # };71//!       #72//!       # let it = It;73//!       # let path = "./path/to/instrs.json";74//!       #75//!       it.detach().context("Failed to detach the important thing")?;76//!77//!       let content = std::fs::read(path)78//!           .with_context(|| format!("Failed to read instrs from {}", path))?;79//!       #80//!       # const _: &str = stringify! {81//!       ...82//!       # };83//!       #84//!       # Ok(())85//!   }86//!   ```87//!88//!   ```console89//!   Error: Failed to read instrs from ./path/to/instrs.json90//!91//!   Caused by:92//!       No such file or directory (os error 2)93//!   ```94//!95//! - Downcasting is supported and can be by value, by shared reference, or by96//!   mutable reference as needed.97//!98//!   ```99//!   # use anyhow::anyhow;100//!   # use std::fmt::{self, Display};101//!   # use std::task::Poll;102//!   #103//!   # #[derive(Debug)]104//!   # enum DataStoreError {105//!   #     Censored(()),106//!   # }107//!   #108//!   # impl Display for DataStoreError {109//!   #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {110//!   #         unimplemented!()111//!   #     }112//!   # }113//!   #114//!   # impl std::error::Error for DataStoreError {}115//!   #116//!   # const REDACTED_CONTENT: () = ();117//!   #118//!   # let error = anyhow!("...");119//!   # let root_cause = &error;120//!   #121//!   # let ret =122//!   // If the error was caused by redaction, then return a123//!   // tombstone instead of the content.124//!   match root_cause.downcast_ref::<DataStoreError>() {125//!       Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),126//!       None => Err(error),127//!   }128//!   # ;129//!   ```130//!131//! - If using Rust &ge; 1.65, a backtrace is captured and printed with the132//!   error if the underlying error type does not already provide its own. In133//!   order to see backtraces, they must be enabled through the environment134//!   variables described in [`std::backtrace`]:135//!136//!   - If you want panics and errors to both have backtraces, set137//!     `RUST_BACKTRACE=1`;138//!   - If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`;139//!   - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and140//!     `RUST_LIB_BACKTRACE=0`.141//!142//!   [`std::backtrace`]: std::backtrace#environment-variables143//!144//! - Anyhow works with any error type that has an impl of `std::error::Error`,145//!   including ones defined in your crate. We do not bundle a `derive(Error)`146//!   macro but you can write the impls yourself or use a standalone macro like147//!   [thiserror].148//!149//!   [thiserror]: https://github.com/dtolnay/thiserror150//!151//!   ```152//!   use thiserror::Error;153//!154//!   #[derive(Error, Debug)]155//!   pub enum FormatError {156//!       #[error("Invalid header (expected {expected:?}, got {found:?})")]157//!       InvalidHeader {158//!           expected: String,159//!           found: String,160//!       },161//!       #[error("Missing attribute: {0}")]162//!       MissingAttribute(String),163//!   }164//!   ```165//!166//! - One-off error messages can be constructed using the `anyhow!` macro, which167//!   supports string interpolation and produces an `anyhow::Error`.168//!169//!   ```170//!   # use anyhow::{anyhow, Result};171//!   #172//!   # fn demo() -> Result<()> {173//!   #     let missing = "...";174//!   return Err(anyhow!("Missing attribute: {}", missing));175//!   #     Ok(())176//!   # }177//!   ```178//!179//!   A `bail!` macro is provided as a shorthand for the same early return.180//!181//!   ```182//!   # use anyhow::{bail, Result};183//!   #184//!   # fn demo() -> Result<()> {185//!   #     let missing = "...";186//!   bail!("Missing attribute: {}", missing);187//!   #     Ok(())188//!   # }189//!   ```190//!191//! <br>192//!193//! # No-std support194//!195//! In no_std mode, almost all of the same API is available and works the same196//! way. To depend on Anyhow in no_std mode, disable our default enabled "std"197//! feature in Cargo.toml. A global allocator is required.198//!199//! ```toml200//! [dependencies]201//! anyhow = { version = "1.0", default-features = false }202//! ```203//!204//! With versions of Rust older than 1.81, no_std mode may require an additional205//! `.map_err(Error::msg)` when working with a non-Anyhow error type inside a206//! function that returns Anyhow's error type, as the trait that `?`-based error207//! conversions are defined by is only available in std in those old versions.208209#![doc(html_root_url = "https://docs.rs/anyhow/1.0.104")]210#![cfg_attr(error_generic_member_access, feature(error_generic_member_access))]211#![no_std]212#![deny(dead_code, unsafe_op_in_unsafe_fn, unused_imports, unused_mut)]213#![allow(214    clippy::doc_markdown,215    clippy::elidable_lifetime_names,216    clippy::enum_glob_use,217    clippy::explicit_auto_deref,218    clippy::extra_unused_type_parameters,219    clippy::incompatible_msrv,220    clippy::let_underscore_untyped,221    clippy::missing_errors_doc,222    clippy::missing_panics_doc,223    clippy::module_name_repetitions,224    clippy::must_use_candidate,225    clippy::needless_doctest_main,226    clippy::needless_lifetimes,227    clippy::new_ret_no_self,228    clippy::redundant_else,229    clippy::return_self_not_must_use,230    clippy::struct_field_names,231    clippy::uninlined_format_args,232    clippy::unused_self,233    clippy::used_underscore_binding,234    clippy::wildcard_imports,235    clippy::wrong_self_convention236)]237#![allow(unknown_lints, mismatched_lifetime_syntaxes)]238239#[cfg(all(240    anyhow_nightly_testing,241    feature = "std",242    not(error_generic_member_access)243))]244compile_error!("Build script probe failed to compile.");245246extern crate alloc;247248#[cfg(feature = "std")]249extern crate std;250251#[macro_use]252mod backtrace;253mod chain;254mod context;255mod ensure;256mod error;257mod fmt;258mod kind;259mod macros;260#[cfg(error_generic_member_access)]261mod nightly;262mod ptr;263mod wrapper;264265use crate::error::ErrorImpl;266use crate::ptr::Own;267use core::fmt::Display;268269#[cfg(all(not(feature = "std"), anyhow_no_core_error))]270use core::fmt::Debug;271272#[cfg(feature = "std")]273use std::error::Error as StdError;274275#[cfg(not(any(feature = "std", anyhow_no_core_error)))]276use core::error::Error as StdError;277278#[cfg(all(not(feature = "std"), anyhow_no_core_error))]279trait StdError: Debug + Display {280    fn source(&self) -> Option<&(dyn StdError + 'static)> {281        None282    }283}284285#[doc(no_inline)]286pub use anyhow as format_err;287288/// The `Error` type, a wrapper around a dynamic error type.289///290/// `Error` works a lot like `Box<dyn std::error::Error>`, but with these291/// differences:292///293/// - `Error` requires that the error is `Send`, `Sync`, and `'static`.294/// - `Error` guarantees that a backtrace is available, even if the underlying295///   error type does not provide one.296/// - `Error` is represented as a narrow pointer &mdash; exactly one word in297///   size instead of two.298///299/// <br>300///301/// # Display representations302///303/// When you print an error object using "{}" or to_string(), only the outermost304/// underlying error or context is printed, not any of the lower level causes.305/// This is exactly as if you had called the Display impl of the error from306/// which you constructed your anyhow::Error.307///308/// ```console309/// Failed to read instrs from ./path/to/instrs.json310/// ```311///312/// To print causes as well using anyhow's default formatting of causes, use the313/// alternate selector "{:#}".314///315/// ```console316/// Failed to read instrs from ./path/to/instrs.json: No such file or directory (os error 2)317/// ```318///319/// The Debug format "{:?}" includes your backtrace if one was captured. Note320/// that this is the representation you get by default if you return an error321/// from `fn main` instead of printing it explicitly yourself.322///323/// ```console324/// Error: Failed to read instrs from ./path/to/instrs.json325///326/// Caused by:327///     No such file or directory (os error 2)328/// ```329///330/// and if there is a backtrace available:331///332/// ```console333/// Error: Failed to read instrs from ./path/to/instrs.json334///335/// Caused by:336///     No such file or directory (os error 2)337///338/// Stack backtrace:339///    0: <E as anyhow::context::ext::StdError>::ext_context340///              at /git/anyhow/src/backtrace.rs:26341///    1: core::result::Result<T,E>::map_err342///              at /git/rustc/src/libcore/result.rs:596343///    2: anyhow::context::<impl anyhow::Context<T,E> for core::result::Result<T,E>>::with_context344///              at /git/anyhow/src/context.rs:58345///    3: testing::main346///              at src/main.rs:5347///    4: std::rt::lang_start348///              at /git/rustc/src/libstd/rt.rs:61349///    5: main350///    6: __libc_start_main351///    7: _start352/// ```353///354/// To see a conventional struct-style Debug representation, use "{:#?}".355///356/// ```console357/// Error {358///     context: "Failed to read instrs from ./path/to/instrs.json",359///     source: Os {360///         code: 2,361///         kind: NotFound,362///         message: "No such file or directory",363///     },364/// }365/// ```366///367/// If none of the built-in representations are appropriate and you would prefer368/// to render the error and its cause chain yourself, it can be done something369/// like this:370///371/// ```372/// use anyhow::{Context, Result};373///374/// fn main() {375///     if let Err(err) = try_main() {376///         eprintln!("ERROR: {}", err);377///         err.chain().skip(1).for_each(|cause| eprintln!("because: {}", cause));378///         std::process::exit(1);379///     }380/// }381///382/// fn try_main() -> Result<()> {383///     # const IGNORE: &str = stringify! {384///     ...385///     # };386///     # Ok(())387/// }388/// ```389#[repr(transparent)]390pub struct Error {391    inner: Own<ErrorImpl>,392}393394/// Iterator of a chain of source errors.395///396/// This type is the iterator returned by [`Error::chain`].397///398/// # Example399///400/// ```401/// use anyhow::Error;402/// use std::io;403///404/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {405///     for cause in error.chain() {406///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {407///             return Some(io_error.kind());408///         }409///     }410///     None411/// }412/// ```413#[cfg(any(feature = "std", not(anyhow_no_core_error)))]414#[derive(Clone)]415pub struct Chain<'a> {416    state: crate::chain::ChainState<'a>,417}418419/// `Result<T, Error>`420///421/// This is a reasonable return type to use throughout your application but also422/// for `fn main`; if you do, failures will be printed along with any423/// [context][Context] and a backtrace if one was captured.424///425/// `anyhow::Result` may be used with one *or* two type parameters.426///427/// ```rust428/// use anyhow::Result;429///430/// # const IGNORE: &str = stringify! {431/// fn demo1() -> Result<T> {...}432///            // ^ equivalent to std::result::Result<T, anyhow::Error>433///434/// fn demo2() -> Result<T, OtherError> {...}435///            // ^ equivalent to std::result::Result<T, OtherError>436/// # };437/// ```438///439/// # Example440///441/// ```442/// # pub trait Deserialize {}443/// #444/// # mod serde_json {445/// #     use super::Deserialize;446/// #     use std::io;447/// #448/// #     pub fn from_str<T: Deserialize>(json: &str) -> io::Result<T> {449/// #         unimplemented!()450/// #     }451/// # }452/// #453/// # #[derive(Debug)]454/// # struct ClusterMap;455/// #456/// # impl Deserialize for ClusterMap {}457/// #458/// use anyhow::Result;459///460/// fn main() -> Result<()> {461///     # return Ok(());462///     let config = std::fs::read_to_string("cluster.json")?;463///     let map: ClusterMap = serde_json::from_str(&config)?;464///     println!("cluster info: {:#?}", map);465///     Ok(())466/// }467/// ```468pub type Result<T, E = Error> = core::result::Result<T, E>;469470/// Provides the `context` method for `Result`.471///472/// This trait is sealed and cannot be implemented for types outside of473/// `anyhow`.474///475/// <br>476///477/// # Example478///479/// ```480/// use anyhow::{Context, Result};481/// use std::fs;482/// use std::path::PathBuf;483///484/// pub struct ImportantThing {485///     path: PathBuf,486/// }487///488/// impl ImportantThing {489///     # const IGNORE: &'static str = stringify! {490///     pub fn detach(&mut self) -> Result<()> {...}491///     # };492///     # fn detach(&mut self) -> Result<()> {493///     #     unimplemented!()494///     # }495/// }496///497/// pub fn do_it(mut it: ImportantThing) -> Result<Vec<u8>> {498///     it.detach().context("Failed to detach the important thing")?;499///500///     let path = &it.path;501///     let content = fs::read(path)502///         .with_context(|| format!("Failed to read instrs from {}", path.display()))?;503///504///     Ok(content)505/// }506/// ```507///508/// When printed, the outermost context would be printed first and the lower509/// level underlying causes would be enumerated below.510///511/// ```console512/// Error: Failed to read instrs from ./path/to/instrs.json513///514/// Caused by:515///     No such file or directory (os error 2)516/// ```517///518/// Refer to the [Display representations] documentation for other forms in519/// which this context chain can be rendered.520///521/// [Display representations]: Error#display-representations522///523/// <br>524///525/// # Effect on downcasting526///527/// After attaching context of type `C` onto an error of type `E`, the resulting528/// `anyhow::Error` may be downcast to `C` **or** to `E`.529///530/// That is, in codebases that rely on downcasting, Anyhow's context supports531/// both of the following use cases:532///533///   - **Attaching context whose type is insignificant onto errors whose type534///     is used in downcasts.**535///536///     In other error libraries whose context is not designed this way, it can537///     be risky to introduce context to existing code because new context might538///     break existing working downcasts. In Anyhow, any downcast that worked539///     before adding context will continue to work after you add a context, so540///     you should freely add human-readable context to errors wherever it would541///     be helpful.542///543///     ```544///     # use anyhow::bail;545///     # use thiserror::Error;546///     #547///     # #[derive(Error, Debug)]548///     # #[error("???")]549///     # struct SuspiciousError;550///     #551///     # fn helper() -> Result<()> {552///     #     bail!(SuspiciousError);553///     # }554///     #555///     use anyhow::{Context, Result};556///557///     fn do_it() -> Result<()> {558///         helper().context("Failed to complete the work")?;559///         # const IGNORE: &str = stringify! {560///         ...561///         # };562///         # unreachable!()563///     }564///565///     fn main() {566///         let err = do_it().unwrap_err();567///         if let Some(e) = err.downcast_ref::<SuspiciousError>() {568///             // If helper() returned SuspiciousError, this downcast will569///             // correctly succeed even with the context in between.570///             # return;571///         }572///         # panic!("expected downcast to succeed");573///     }574///     ```575///576///   - **Attaching context whose type is used in downcasts onto errors whose577///     type is insignificant.**578///579///     Some codebases prefer to use machine-readable context to categorize580///     lower level errors in a way that will be actionable to higher levels of581///     the application.582///583///     ```584///     # use anyhow::bail;585///     # use thiserror::Error;586///     #587///     # #[derive(Error, Debug)]588///     # #[error("???")]589///     # struct HelperFailed;590///     #591///     # fn helper() -> Result<()> {592///     #     bail!("no such file or directory");593///     # }594///     #595///     use anyhow::{Context, Result};596///597///     fn do_it() -> Result<()> {598///         helper().context(HelperFailed)?;599///         # const IGNORE: &str = stringify! {600///         ...601///         # };602///         # unreachable!()603///     }604///605///     fn main() {606///         let err = do_it().unwrap_err();607///         if let Some(e) = err.downcast_ref::<HelperFailed>() {608///             // If helper failed, this downcast will succeed because609///             // HelperFailed is the context that has been attached to610///             // that error.611///             # return;612///         }613///         # panic!("expected downcast to succeed");614///     }615///     ```616pub trait Context<T, E>: context::private::Sealed {617    /// Wrap the error value with additional context.618    fn context<C>(self, context: C) -> Result<T, Error>619    where620        C: Display + Send + Sync + 'static;621622    /// Wrap the error value with additional context that is evaluated lazily623    /// only once an error does occur.624    fn with_context<C, F>(self, f: F) -> Result<T, Error>625    where626        C: Display + Send + Sync + 'static,627        F: FnOnce() -> C;628}629630/// Equivalent to `Ok::<_, anyhow::Error>(value)`.631///632/// This simplifies creation of an `anyhow::Result` in places where type633/// inference cannot deduce the `E` type of the result &mdash; without needing634/// to write `Ok::<_, anyhow::Error>(value)`.635///636/// One might think that `anyhow::Result::Ok(value)` would work in such cases637/// but it does not.638///639/// ```console640/// error[E0282]: type annotations needed for `std::result::Result<i32, E>`641///   --> src/main.rs:11:13642///    |643/// 11 |     let _ = anyhow::Result::Ok(1);644///    |         -   ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `E` declared on the enum `Result`645///    |         |646///    |         consider giving this pattern the explicit type `std::result::Result<i32, E>`, where the type parameter `E` is specified647/// ```648#[allow(non_snake_case)]649#[inline]650pub fn Ok<T>(value: T) -> Result<T> {651    Result::Ok(value)652}653654// Not public API. Referenced by macro-generated code.655#[doc(hidden)]656pub mod __private {657    use self::not::Bool;658    use crate::Error;659    use alloc::fmt;660    use core::fmt::Arguments;661662    #[doc(hidden)]663    pub use crate::ensure::{BothDebug, NotBothDebug};664    #[doc(hidden)]665    pub use alloc::format;666    #[doc(hidden)]667    pub use core::result::Result::Err;668    #[doc(hidden)]669    pub use core::{concat, format_args, stringify};670671    #[doc(hidden)]672    pub mod kind {673        #[doc(hidden)]674        pub use crate::kind::{AdhocKind, TraitKind};675676        #[cfg(any(feature = "std", not(anyhow_no_core_error)))]677        #[doc(hidden)]678        pub use crate::kind::BoxedKind;679    }680681    #[doc(hidden)]682    #[inline]683    #[cold]684    pub fn format_err(args: Arguments) -> Error {685        if let Some(message) = args.as_str() {686            // anyhow!("literal"), can downcast to &'static str687            Error::msg(message)688        } else {689            // anyhow!("interpolate {var}"), can downcast to String690            Error::msg(fmt::format(args))691        }692    }693694    #[doc(hidden)]695    #[inline]696    #[cold]697    #[must_use]698    pub fn must_use(error: Error) -> Error {699        error700    }701702    #[doc(hidden)]703    #[inline]704    pub fn not(cond: impl Bool) -> bool {705        cond.not()706    }707708    mod not {709        #[doc(hidden)]710        pub trait Bool {711            fn not(self) -> bool;712        }713714        impl Bool for bool {715            #[inline]716            fn not(self) -> bool {717                !self718            }719        }720721        impl Bool for &bool {722            #[inline]723            fn not(self) -> bool {724                !*self725            }726        }727    }728}