Skip to content
Myr

lib.rs

This file

Path

src/lib.rs

666 lines · 20.4 KiB · Rust

Last changed by

Release 1.0.49David Tolnaybefore adoptiona5a98e0

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&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K6//!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 the nightly channel, or stable with `features = ["backtrace"]`, a132//!   backtrace is captured and printed with the error if the underlying error133//!   type does not already provide its own. In order to see backtraces, they134//!   must be enabled through the environment variables described in135//!   [`std::backtrace`]:136//!137//!   - If you want panics and errors to both have backtraces, set138//!     `RUST_BACKTRACE=1`;139//!   - If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`;140//!   - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and141//!     `RUST_LIB_BACKTRACE=0`.142//!143//!   The tracking issue for this feature is [rust-lang/rust#53487].144//!145//!   [`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variables146//!   [rust-lang/rust#53487]: https://github.com/rust-lang/rust/issues/53487147//!148//! - Anyhow works with any error type that has an impl of `std::error::Error`,149//!   including ones defined in your crate. We do not bundle a `derive(Error)`150//!   macro but you can write the impls yourself or use a standalone macro like151//!   [thiserror].152//!153//!   [thiserror]: https://github.com/dtolnay/thiserror154//!155//!   ```156//!   use thiserror::Error;157//!158//!   #[derive(Error, Debug)]159//!   pub enum FormatError {160//!       #[error("Invalid header (expected {expected:?}, got {found:?})")]161//!       InvalidHeader {162//!           expected: String,163//!           found: String,164//!       },165//!       #[error("Missing attribute: {0}")]166//!       MissingAttribute(String),167//!   }168//!   ```169//!170//! - One-off error messages can be constructed using the `anyhow!` macro, which171//!   supports string interpolation and produces an `anyhow::Error`.172//!173//!   ```174//!   # use anyhow::{anyhow, Result};175//!   #176//!   # fn demo() -> Result<()> {177//!   #     let missing = "...";178//!   return Err(anyhow!("Missing attribute: {}", missing));179//!   #     Ok(())180//!   # }181//!   ```182//!183//!   A `bail!` macro is provided as a shorthand for the same early return.184//!185//!   ```186//!   # use anyhow::{bail, Result};187//!   #188//!   # fn demo() -> Result<()> {189//!   #     let missing = "...";190//!   bail!("Missing attribute: {}", missing);191//!   #     Ok(())192//!   # }193//!   ```194//!195//! <br>196//!197//! # No-std support198//!199//! In no_std mode, the same API is almost all available and works the same way.200//! To depend on Anyhow in no_std mode, disable our default enabled "std"201//! feature in Cargo.toml. A global allocator is required.202//!203//! ```toml204//! [dependencies]205//! anyhow = { version = "1.0", default-features = false }206//! ```207//!208//! Since the `?`-based error conversions would normally rely on the209//! `std::error::Error` trait which is only available through std, no_std mode210//! will require an explicit `.map_err(Error::msg)` when working with a211//! non-Anyhow error type inside a function that returns Anyhow's error type.212213#![doc(html_root_url = "https://docs.rs/anyhow/1.0.49")]214#![cfg_attr(backtrace, feature(backtrace))]215#![cfg_attr(doc_cfg, feature(doc_cfg))]216#![cfg_attr(not(feature = "std"), no_std)]217#![deny(dead_code, unused_imports, unused_mut)]218#![allow(219    clippy::doc_markdown,220    clippy::enum_glob_use,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::new_ret_no_self,227    clippy::redundant_else,228    clippy::unused_self,229    clippy::used_underscore_binding,230    clippy::wildcard_imports,231    clippy::wrong_self_convention232)]233234extern crate alloc;235236#[macro_use]237mod backtrace;238mod chain;239mod context;240mod ensure;241mod error;242mod fmt;243mod kind;244mod macros;245mod ptr;246mod wrapper;247248use crate::error::ErrorImpl;249use crate::ptr::Own;250use core::fmt::Display;251252#[cfg(not(feature = "std"))]253use core::fmt::Debug;254255#[cfg(feature = "std")]256use std::error::Error as StdError;257258#[cfg(not(feature = "std"))]259trait StdError: Debug + Display {260    fn source(&self) -> Option<&(dyn StdError + 'static)> {261        None262    }263}264265pub use anyhow as format_err;266267/// The `Error` type, a wrapper around a dynamic error type.268///269/// `Error` works a lot like `Box<dyn std::error::Error>`, but with these270/// differences:271///272/// - `Error` requires that the error is `Send`, `Sync`, and `'static`.273/// - `Error` guarantees that a backtrace is available, even if the underlying274///   error type does not provide one.275/// - `Error` is represented as a narrow pointer &mdash; exactly one word in276///   size instead of two.277///278/// <br>279///280/// # Display representations281///282/// When you print an error object using "{}" or to_string(), only the outermost283/// underlying error or context is printed, not any of the lower level causes.284/// This is exactly as if you had called the Display impl of the error from285/// which you constructed your anyhow::Error.286///287/// ```console288/// Failed to read instrs from ./path/to/instrs.json289/// ```290///291/// To print causes as well using anyhow's default formatting of causes, use the292/// alternate selector "{:#}".293///294/// ```console295/// Failed to read instrs from ./path/to/instrs.json: No such file or directory (os error 2)296/// ```297///298/// The Debug format "{:?}" includes your backtrace if one was captured. Note299/// that this is the representation you get by default if you return an error300/// from `fn main` instead of printing it explicitly yourself.301///302/// ```console303/// Error: Failed to read instrs from ./path/to/instrs.json304///305/// Caused by:306///     No such file or directory (os error 2)307/// ```308///309/// and if there is a backtrace available:310///311/// ```console312/// Error: Failed to read instrs from ./path/to/instrs.json313///314/// Caused by:315///     No such file or directory (os error 2)316///317/// Stack backtrace:318///    0: <E as anyhow::context::ext::StdError>::ext_context319///              at /git/anyhow/src/backtrace.rs:26320///    1: core::result::Result<T,E>::map_err321///              at /git/rustc/src/libcore/result.rs:596322///    2: anyhow::context::<impl anyhow::Context<T,E> for core::result::Result<T,E>>::with_context323///              at /git/anyhow/src/context.rs:58324///    3: testing::main325///              at src/main.rs:5326///    4: std::rt::lang_start327///              at /git/rustc/src/libstd/rt.rs:61328///    5: main329///    6: __libc_start_main330///    7: _start331/// ```332///333/// To see a conventional struct-style Debug representation, use "{:#?}".334///335/// ```console336/// Error {337///     context: "Failed to read instrs from ./path/to/instrs.json",338///     source: Os {339///         code: 2,340///         kind: NotFound,341///         message: "No such file or directory",342///     },343/// }344/// ```345///346/// If none of the built-in representations are appropriate and you would prefer347/// to render the error and its cause chain yourself, it can be done something348/// like this:349///350/// ```351/// use anyhow::{Context, Result};352///353/// fn main() {354///     if let Err(err) = try_main() {355///         eprintln!("ERROR: {}", err);356///         err.chain().skip(1).for_each(|cause| eprintln!("because: {}", cause));357///         std::process::exit(1);358///     }359/// }360///361/// fn try_main() -> Result<()> {362///     # const IGNORE: &str = stringify! {363///     ...364///     # };365///     # Ok(())366/// }367/// ```368#[repr(transparent)]369pub struct Error {370    inner: Own<ErrorImpl>,371}372373/// Iterator of a chain of source errors.374///375/// This type is the iterator returned by [`Error::chain`].376///377/// # Example378///379/// ```380/// use anyhow::Error;381/// use std::io;382///383/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {384///     for cause in error.chain() {385///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {386///             return Some(io_error.kind());387///         }388///     }389///     None390/// }391/// ```392#[cfg(feature = "std")]393#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]394#[derive(Clone)]395pub struct Chain<'a> {396    state: crate::chain::ChainState<'a>,397}398399/// `Result<T, Error>`400///401/// This is a reasonable return type to use throughout your application but also402/// for `fn main`; if you do, failures will be printed along with any403/// [context][Context] and a backtrace if one was captured.404///405/// `anyhow::Result` may be used with one *or* two type parameters.406///407/// ```rust408/// use anyhow::Result;409///410/// # const IGNORE: &str = stringify! {411/// fn demo1() -> Result<T> {...}412///            // ^ equivalent to std::result::Result<T, anyhow::Error>413///414/// fn demo2() -> Result<T, OtherError> {...}415///            // ^ equivalent to std::result::Result<T, OtherError>416/// # };417/// ```418///419/// # Example420///421/// ```422/// # pub trait Deserialize {}423/// #424/// # mod serde_json {425/// #     use super::Deserialize;426/// #     use std::io;427/// #428/// #     pub fn from_str<T: Deserialize>(json: &str) -> io::Result<T> {429/// #         unimplemented!()430/// #     }431/// # }432/// #433/// # #[derive(Debug)]434/// # struct ClusterMap;435/// #436/// # impl Deserialize for ClusterMap {}437/// #438/// use anyhow::Result;439///440/// fn main() -> Result<()> {441///     # return Ok(());442///     let config = std::fs::read_to_string("cluster.json")?;443///     let map: ClusterMap = serde_json::from_str(&config)?;444///     println!("cluster info: {:#?}", map);445///     Ok(())446/// }447/// ```448pub type Result<T, E = Error> = core::result::Result<T, E>;449450/// Provides the `context` method for `Result`.451///452/// This trait is sealed and cannot be implemented for types outside of453/// `anyhow`.454///455/// <br>456///457/// # Example458///459/// ```460/// use anyhow::{Context, Result};461/// use std::fs;462/// use std::path::PathBuf;463///464/// pub struct ImportantThing {465///     path: PathBuf,466/// }467///468/// impl ImportantThing {469///     # const IGNORE: &'static str = stringify! {470///     pub fn detach(&mut self) -> Result<()> {...}471///     # };472///     # fn detach(&mut self) -> Result<()> {473///     #     unimplemented!()474///     # }475/// }476///477/// pub fn do_it(mut it: ImportantThing) -> Result<Vec<u8>> {478///     it.detach().context("Failed to detach the important thing")?;479///480///     let path = &it.path;481///     let content = fs::read(path)482///         .with_context(|| format!("Failed to read instrs from {}", path.display()))?;483///484///     Ok(content)485/// }486/// ```487///488/// When printed, the outermost context would be printed first and the lower489/// level underlying causes would be enumerated below.490///491/// ```console492/// Error: Failed to read instrs from ./path/to/instrs.json493///494/// Caused by:495///     No such file or directory (os error 2)496/// ```497///498/// <br>499///500/// # Effect on downcasting501///502/// After attaching context of type `C` onto an error of type `E`, the resulting503/// `anyhow::Error` may be downcast to `C` **or** to `E`.504///505/// That is, in codebases that rely on downcasting, Anyhow's context supports506/// both of the following use cases:507///508///   - **Attaching context whose type is insignificant onto errors whose type509///     is used in downcasts.**510///511///     In other error libraries whose context is not designed this way, it can512///     be risky to introduce context to existing code because new context might513///     break existing working downcasts. In Anyhow, any downcast that worked514///     before adding context will continue to work after you add a context, so515///     you should freely add human-readable context to errors wherever it would516///     be helpful.517///518///     ```519///     # use anyhow::bail;520///     # use thiserror::Error;521///     #522///     # #[derive(Error, Debug)]523///     # #[error("???")]524///     # struct SuspiciousError;525///     #526///     # fn helper() -> Result<()> {527///     #     bail!(SuspiciousError);528///     # }529///     #530///     use anyhow::{Context, Result};531///532///     fn do_it() -> Result<()> {533///         helper().context("Failed to complete the work")?;534///         # const IGNORE: &str = stringify! {535///         ...536///         # };537///         # unreachable!()538///     }539///540///     fn main() {541///         let err = do_it().unwrap_err();542///         if let Some(e) = err.downcast_ref::<SuspiciousError>() {543///             // If helper() returned SuspiciousError, this downcast will544///             // correctly succeed even with the context in between.545///             # return;546///         }547///         # panic!("expected downcast to succeed");548///     }549///     ```550///551///   - **Attaching context whose type is used in downcasts onto errors whose552///     type is insignificant.**553///554///     Some codebases prefer to use machine-readable context to categorize555///     lower level errors in a way that will be actionable to higher levels of556///     the application.557///558///     ```559///     # use anyhow::bail;560///     # use thiserror::Error;561///     #562///     # #[derive(Error, Debug)]563///     # #[error("???")]564///     # struct HelperFailed;565///     #566///     # fn helper() -> Result<()> {567///     #     bail!("no such file or directory");568///     # }569///     #570///     use anyhow::{Context, Result};571///572///     fn do_it() -> Result<()> {573///         helper().context(HelperFailed)?;574///         # const IGNORE: &str = stringify! {575///         ...576///         # };577///         # unreachable!()578///     }579///580///     fn main() {581///         let err = do_it().unwrap_err();582///         if let Some(e) = err.downcast_ref::<HelperFailed>() {583///             // If helper failed, this downcast will succeed because584///             // HelperFailed is the context that has been attached to585///             // that error.586///             # return;587///         }588///         # panic!("expected downcast to succeed");589///     }590///     ```591pub trait Context<T, E>: context::private::Sealed {592    /// Wrap the error value with additional context.593    fn context<C>(self, context: C) -> Result<T, Error>594    where595        C: Display + Send + Sync + 'static;596597    /// Wrap the error value with additional context that is evaluated lazily598    /// only once an error does occur.599    fn with_context<C, F>(self, f: F) -> Result<T, Error>600    where601        C: Display + Send + Sync + 'static,602        F: FnOnce() -> C;603}604605/// Equivalent to `Ok::<_, anyhow::Error>(value)`.606///607/// This simplifies creation of an anyhow::Result in places where type inference608/// cannot deduce the `E` type of the result &mdash; without needing to write609/// `Ok::<_, anyhow::Error>(value)`.610///611/// One might think that `anyhow::Result::Ok(value)` would work in such cases612/// but it does not.613///614/// ```console615/// error[E0282]: type annotations needed for `std::result::Result<i32, E>`616///   --> src/main.rs:11:13617///    |618/// 11 |     let _ = anyhow::Result::Ok(1);619///    |         -   ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `E` declared on the enum `Result`620///    |         |621///    |         consider giving this pattern the explicit type `std::result::Result<i32, E>`, where the type parameter `E` is specified622/// ```623#[doc(hidden)]624#[allow(non_snake_case)]625pub fn Ok<T>(t: T) -> Result<T> {626    Result::Ok(t)627}628629// Not public API. Referenced by macro-generated code.630#[doc(hidden)]631pub mod private {632    use crate::Error;633    use alloc::fmt;634    use core::fmt::Arguments;635636    pub use crate::ensure::{BothDebug, NotBothDebug};637    pub use alloc::format;638    pub use core::result::Result::Err;639    pub use core::{concat, format_args, stringify};640641    #[doc(hidden)]642    pub mod kind {643        pub use crate::kind::{AdhocKind, TraitKind};644645        #[cfg(feature = "std")]646        pub use crate::kind::BoxedKind;647    }648649    #[doc(hidden)]650    #[inline]651    #[cold]652    pub fn format_err(args: Arguments) -> Error {653        #[cfg(anyhow_no_fmt_arguments_as_str)]654        let fmt_arguments_as_str = None::<&str>;655        #[cfg(not(anyhow_no_fmt_arguments_as_str))]656        let fmt_arguments_as_str = args.as_str();657658        if let Some(message) = fmt_arguments_as_str {659            // anyhow!("literal"), can downcast to &'static str660            Error::msg(message)661        } else {662            // anyhow!("interpolate {var}"), can downcast to String663            Error::msg(fmt::format(args))664        }665    }666}