lib.rs
This file
Path
src/lib.rs
679 lines · 20.7 KiB · Rust
Last changed by
Release 1.0.57David Tolnaybefore adoptionf64ca0a
History of this fileTake it
The walk stopped after 200 commits: lines older than 00545d5 point at it.
Add crosslink icons to top of rustdocDavid Tolnaybefore adoption16f607e
lines 1–8why, one step back1//! [![github]](https://github.com/dtolnay/anyhow) [![crates-io]](https://crates.io/crates/anyhow) [![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//!Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 9–130why, one step back9//! 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//!Mirror PR 162 from readme to rustdocDavid Tolnaybefore adoptionb3c5e25
lines 131–135why, one step back131//! - 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`]:Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea
lines 136–142why, one step back136//!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//!Rephrase nightly backtrace noteDavid Tolnaybefore adoptione46df9f
line 143why, one step back143//! The tracking issue for this feature is [rust-lang/rust#53487].Merge pull request #73 from lzybkr/nightly_in_docsDavid Tolnaybefore adoption946bff8
line 144why, one step back144//!Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea
line 145why, one step back145//! [`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variablesRephrase nightly backtrace noteDavid Tolnaybefore adoptione46df9f
line 146why, one step back146//! [rust-lang/rust#53487]: https://github.com/rust-lang/rust/issues/53487Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 147–181why, one step back147//!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//! ```Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 182why, one step back182//!Copy bail mention from readme to rustdocDavid Tolnaybefore adoptionc25be95
lines 183–194why, one step back183//! 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//!Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
lines 195–211why, one step back195//! <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.Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
line 212why, one step back212Release 1.0.57David Tolnaybefore adoptionf64ca0a
line 213why, one step back213#![doc(html_root_url = "https://docs.rs/anyhow/1.0.57")]Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
line 214why, one step back214#![cfg_attr(backtrace, feature(backtrace))]Merge pull request #78 from dtolnay/cfgDavid Tolnaybefore adoptione2eb1f5
line 215why, one step back215#![cfg_attr(doc_cfg, feature(doc_cfg))]Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 216why, one step back216#![cfg_attr(not(feature = "std"), no_std)]Catch some warnings in addr_of-related codepathsDavid Tolnaybefore adoption827bb9d
line 217why, one step back217#![deny(dead_code, unused_imports, unused_mut)]Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
line 218why, one step back218#![allow(Opt in to pedantic clippy lintsDavid Tolnaybefore adoption318db92
lines 219–221why, one step back219 clippy::doc_markdown,220 clippy::enum_glob_use,221 clippy::missing_errors_doc,Ignore new missing_panics_doc pedantic clippy lintDavid Tolnaybefore adoption1631007
line 222why, one step back222 clippy::missing_panics_doc,Opt in to pedantic clippy lintsDavid Tolnaybefore adoption318db92
lines 223–224why, one step back223 clippy::module_name_repetitions,224 clippy::must_use_candidate,Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 225–226why, one step back225 clippy::needless_doctest_main,226 clippy::new_ret_no_self,Ignore redundant_else pedantic clippy lintDavid Tolnaybefore adoption2987c9b
line 227why, one step back227 clippy::redundant_else,Ignore return_self_not_must_use clippy lintDavid Tolnaybefore adoptiona3f7160
line 228why, one step back228 clippy::return_self_not_must_use,Opt in to pedantic clippy lintsDavid Tolnaybefore adoption318db92
lines 229–231why, one step back229 clippy::unused_self,230 clippy::used_underscore_binding,231 clippy::wildcard_imports,Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 232–234why, one step back232 clippy::wrong_self_convention233)]234Merge pull request #178 from dtolnay/upDavid Tolnaybefore adoption3c586dd
line 235why, one step back235extern crate alloc;Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 236why, one step back236Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 237–240why, one step back237#[macro_use]238mod backtrace;239mod chain;240mod context;Merge pull request #193 from dtolnay/ensureDavid Tolnaybefore adoptione05df5f
line 241why, one step back241mod ensure;Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 242–245why, one step back242mod error;243mod fmt;244mod kind;245mod macros;Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2
line 246why, one step back246mod ptr;Move transparent wrapper errors to own moduleDavid Tolnaybefore adoptionba0b307
line 247why, one step back247mod wrapper;Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
line 248why, one step back248Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 249why, one step back249use crate::error::ErrorImpl;Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2
line 250why, one step back250use crate::ptr::Own;Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
lines 251–252why, one step back251use core::fmt::Display;252Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
line 253why, one step back253#[cfg(not(feature = "std"))]Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 254why, one step back254use core::fmt::Debug;Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
line 255why, one step back255Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
lines 256–257why, one step back256#[cfg(feature = "std")]257use std::error::Error as StdError;Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
line 258why, one step back258Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
lines 259–265why, one step back259#[cfg(not(feature = "std"))]260trait StdError: Debug + Display {261 fn source(&self) -> Option<&(dyn StdError + 'static)> {262 None263 }264}265Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 266–307why, one step back266pub use anyhow as format_err;267268/// The `Error` type, a wrapper around a dynamic error type.269///270/// `Error` works a lot like `Box<dyn std::error::Error>`, but with these271/// differences:272///273/// - `Error` requires that the error is `Send`, `Sync`, and `'static`.274/// - `Error` guarantees that a backtrace is available, even if the underlying275/// error type does not provide one.276/// - `Error` is represented as a narrow pointer — exactly one word in277/// size instead of two.278///279/// <br>280///281/// # Display representations282///283/// When you print an error object using "{}" or to_string(), only the outermost284/// underlying error or context is printed, not any of the lower level causes.285/// This is exactly as if you had called the Display impl of the error from286/// which you constructed your anyhow::Error.287///288/// ```console289/// Failed to read instrs from ./path/to/instrs.json290/// ```291///292/// To print causes as well using anyhow's default formatting of causes, use the293/// alternate selector "{:#}".294///295/// ```console296/// Failed to read instrs from ./path/to/instrs.json: No such file or directory (os error 2)297/// ```298///299/// The Debug format "{:?}" includes your backtrace if one was captured. Note300/// that this is the representation you get by default if you return an error301/// from `fn main` instead of printing it explicitly yourself.302///303/// ```console304/// Error: Failed to read instrs from ./path/to/instrs.json305///306/// Caused by:307/// No such file or directory (os error 2)Show an example of {:?} without backtraceDavid Tolnaybefore adoptionf7424bd
lines 308–316why, one step back308/// ```309///310/// and if there is a backtrace available:311///312/// ```console313/// Error: Failed to read instrs from ./path/to/instrs.json314///315/// Caused by:316/// No such file or directory (os error 2)Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 317–368why, one step back317///318/// Stack backtrace:319/// 0: <E as anyhow::context::ext::StdError>::ext_context320/// at /git/anyhow/src/backtrace.rs:26321/// 1: core::result::Result<T,E>::map_err322/// at /git/rustc/src/libcore/result.rs:596323/// 2: anyhow::context::<impl anyhow::Context<T,E> for core::result::Result<T,E>>::with_context324/// at /git/anyhow/src/context.rs:58325/// 3: testing::main326/// at src/main.rs:5327/// 4: std::rt::lang_start328/// at /git/rustc/src/libstd/rt.rs:61329/// 5: main330/// 6: __libc_start_main331/// 7: _start332/// ```333///334/// To see a conventional struct-style Debug representation, use "{:#?}".335///336/// ```console337/// Error {338/// context: "Failed to read instrs from ./path/to/instrs.json",339/// source: Os {340/// code: 2,341/// kind: NotFound,342/// message: "No such file or directory",343/// },344/// }345/// ```346///347/// If none of the built-in representations are appropriate and you would prefer348/// to render the error and its cause chain yourself, it can be done something349/// like this:350///351/// ```352/// use anyhow::{Context, Result};353///354/// fn main() {355/// if let Err(err) = try_main() {356/// eprintln!("ERROR: {}", err);357/// err.chain().skip(1).for_each(|cause| eprintln!("because: {}", cause));358/// std::process::exit(1);359/// }360/// }361///362/// fn try_main() -> Result<()> {363/// # const IGNORE: &str = stringify! {364/// ...365/// # };366/// # Ok(())367/// }368/// ```Merge pull request 132 from dtolnay/reprDavid Tolnaybefore adoption0650f43
line 369why, one step back369#[repr(transparent)]Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
line 370why, one step back370pub struct Error {Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2
line 371why, one step back371 inner: Own<ErrorImpl>,Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 372–392why, one step back372}373374/// Iterator of a chain of source errors.375///376/// This type is the iterator returned by [`Error::chain`].377///378/// # Example379///380/// ```381/// use anyhow::Error;382/// use std::io;383///384/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {385/// for cause in error.chain() {386/// if let Some(io_error) = cause.downcast_ref::<io::Error>() {387/// return Some(io_error.kind());388/// }389/// }390/// None391/// }392/// ```Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 393why, one step back393#[cfg(feature = "std")]Merge pull request #128 from dtolnay/doc-cfgDavid Tolnaybefore adoption0c0e41f
line 394why, one step back394#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 395–396why, one step back395#[derive(Clone)]396pub struct Chain<'a> {Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 397why, one step back397 state: crate::chain::ChainState<'a>,Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 398–448why, one step back398}399400/// `Result<T, Error>`401///402/// This is a reasonable return type to use throughout your application but also403/// for `fn main`; if you do, failures will be printed along with any404/// [context][Context] and a backtrace if one was captured.405///406/// `anyhow::Result` may be used with one *or* two type parameters.407///408/// ```rust409/// use anyhow::Result;410///411/// # const IGNORE: &str = stringify! {412/// fn demo1() -> Result<T> {...}413/// // ^ equivalent to std::result::Result<T, anyhow::Error>414///415/// fn demo2() -> Result<T, OtherError> {...}416/// // ^ equivalent to std::result::Result<T, OtherError>417/// # };418/// ```419///420/// # Example421///422/// ```423/// # pub trait Deserialize {}424/// #425/// # mod serde_json {426/// # use super::Deserialize;427/// # use std::io;428/// #429/// # pub fn from_str<T: Deserialize>(json: &str) -> io::Result<T> {430/// # unimplemented!()431/// # }432/// # }433/// #434/// # #[derive(Debug)]435/// # struct ClusterMap;436/// #437/// # impl Deserialize for ClusterMap {}438/// #439/// use anyhow::Result;440///441/// fn main() -> Result<()> {442/// # return Ok(());443/// let config = std::fs::read_to_string("cluster.json")?;444/// let map: ClusterMap = serde_json::from_str(&config)?;445/// println!("cluster info: {:#?}", map);446/// Ok(())447/// }448/// ```Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 449why, one step back449pub type Result<T, E = Error> = core::result::Result<T, E>;Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 450–498why, one step back450451/// Provides the `context` method for `Result`.452///453/// This trait is sealed and cannot be implemented for types outside of454/// `anyhow`.455///456/// <br>457///458/// # Example459///460/// ```461/// use anyhow::{Context, Result};462/// use std::fs;463/// use std::path::PathBuf;464///465/// pub struct ImportantThing {466/// path: PathBuf,467/// }468///469/// impl ImportantThing {470/// # const IGNORE: &'static str = stringify! {471/// pub fn detach(&mut self) -> Result<()> {...}472/// # };473/// # fn detach(&mut self) -> Result<()> {474/// # unimplemented!()475/// # }476/// }477///478/// pub fn do_it(mut it: ImportantThing) -> Result<Vec<u8>> {479/// it.detach().context("Failed to detach the important thing")?;480///481/// let path = &it.path;482/// let content = fs::read(path)483/// .with_context(|| format!("Failed to read instrs from {}", path.display()))?;484///485/// Ok(content)486/// }487/// ```488///489/// When printed, the outermost context would be printed first and the lower490/// level underlying causes would be enumerated below.491///492/// ```console493/// Error: Failed to read instrs from ./path/to/instrs.json494///495/// Caused by:496/// No such file or directory (os error 2)497/// ```498///Add link from Context docs to Display representationsDavid Tolnaybefore adoption6a31772
lines 499–503why, one step back499/// Refer to the [Display representations] documentation for other forms in500/// which this context chain can be rendered.501///502/// [Display representations]: Error#display-representations503///Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 504–610why, one step back504/// <br>505///506/// # Effect on downcasting507///508/// After attaching context of type `C` onto an error of type `E`, the resulting509/// `anyhow::Error` may be downcast to `C` **or** to `E`.510///511/// That is, in codebases that rely on downcasting, Anyhow's context supports512/// both of the following use cases:513///514/// - **Attaching context whose type is insignificant onto errors whose type515/// is used in downcasts.**516///517/// In other error libraries whose context is not designed this way, it can518/// be risky to introduce context to existing code because new context might519/// break existing working downcasts. In Anyhow, any downcast that worked520/// before adding context will continue to work after you add a context, so521/// you should freely add human-readable context to errors wherever it would522/// be helpful.523///524/// ```525/// # use anyhow::bail;526/// # use thiserror::Error;527/// #528/// # #[derive(Error, Debug)]529/// # #[error("???")]530/// # struct SuspiciousError;531/// #532/// # fn helper() -> Result<()> {533/// # bail!(SuspiciousError);534/// # }535/// #536/// use anyhow::{Context, Result};537///538/// fn do_it() -> Result<()> {539/// helper().context("Failed to complete the work")?;540/// # const IGNORE: &str = stringify! {541/// ...542/// # };543/// # unreachable!()544/// }545///546/// fn main() {547/// let err = do_it().unwrap_err();548/// if let Some(e) = err.downcast_ref::<SuspiciousError>() {549/// // If helper() returned SuspiciousError, this downcast will550/// // correctly succeed even with the context in between.551/// # return;552/// }553/// # panic!("expected downcast to succeed");554/// }555/// ```556///557/// - **Attaching context whose type is used in downcasts onto errors whose558/// type is insignificant.**559///560/// Some codebases prefer to use machine-readable context to categorize561/// lower level errors in a way that will be actionable to higher levels of562/// the application.563///564/// ```565/// # use anyhow::bail;566/// # use thiserror::Error;567/// #568/// # #[derive(Error, Debug)]569/// # #[error("???")]570/// # struct HelperFailed;571/// #572/// # fn helper() -> Result<()> {573/// # bail!("no such file or directory");574/// # }575/// #576/// use anyhow::{Context, Result};577///578/// fn do_it() -> Result<()> {579/// helper().context(HelperFailed)?;580/// # const IGNORE: &str = stringify! {581/// ...582/// # };583/// # unreachable!()584/// }585///586/// fn main() {587/// let err = do_it().unwrap_err();588/// if let Some(e) = err.downcast_ref::<HelperFailed>() {589/// // If helper failed, this downcast will succeed because590/// // HelperFailed is the context that has been attached to591/// // that error.592/// # return;593/// }594/// # panic!("expected downcast to succeed");595/// }596/// ```597pub trait Context<T, E>: context::private::Sealed {598 /// Wrap the error value with additional context.599 fn context<C>(self, context: C) -> Result<T, Error>600 where601 C: Display + Send + Sync + 'static;602603 /// Wrap the error value with additional context that is evaluated lazily604 /// only once an error does occur.605 fn with_context<C, F>(self, f: F) -> Result<T, Error>606 where607 C: Display + Send + Sync + 'static,608 F: FnOnce() -> C;609}610Show doc for Ok fnDavid Tolnaybefore adoption97cff68
line 611why, one step back611/// Equivalent to Ok::<_, anyhow::Error>(value).Add anyhow::OkDavid Tolnaybefore adoption2d4bb64
lines 612–633why, one step back612///613/// This simplifies creation of an anyhow::Result in places where type inference614/// cannot deduce the `E` type of the result — without needing to write615/// `Ok::<_, anyhow::Error>(value)`.616///617/// One might think that `anyhow::Result::Ok(value)` would work in such cases618/// but it does not.619///620/// ```console621/// error[E0282]: type annotations needed for `std::result::Result<i32, E>`622/// --> src/main.rs:11:13623/// |624/// 11 | let _ = anyhow::Result::Ok(1);625/// | - ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `E` declared on the enum `Result`626/// | |627/// | consider giving this pattern the explicit type `std::result::Result<i32, E>`, where the type parameter `E` is specified628/// ```629#[allow(non_snake_case)]630pub fn Ok<T>(t: T) -> Result<T> {631 Result::Ok(t)632}633Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
lines 634–636why, one step back634// Not public API. Referenced by macro-generated code.635#[doc(hidden)]636pub mod private {Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c
lines 637–638why, one step back637 use crate::Error;638 use alloc::fmt;Merge pull request #185 from dtolnay/fmtDavid Tolnaybefore adoptiona7f6089
line 639why, one step back639 use core::fmt::Arguments;Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c
line 640why, one step back640Merge pull request #193 from dtolnay/ensureDavid Tolnaybefore adoptione05df5f
line 641why, one step back641 pub use crate::ensure::{BothDebug, NotBothDebug};Merge pull request #179 from dtolnay/upDavid Tolnaybefore adoptioncd03064
line 642why, one step back642 pub use alloc::format;Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 643why, one step back643 pub use core::result::Result::Err;Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c
line 644why, one step back644 pub use core::{concat, format_args, stringify};Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
line 645why, one step back645Remove need for allow(unused_imports)David Tolnaybefore adoption4f123ae
lines 646–647why, one step back646 #[doc(hidden)]647 pub mod kind {Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9
lines 648–651why, one step back648 pub use crate::kind::{AdhocKind, TraitKind};649650 #[cfg(feature = "std")]651 pub use crate::kind::BoxedKind;Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c
lines 652–654why, one step back652 }653654 #[doc(hidden)]Merge pull request #185 from dtolnay/fmtDavid Tolnaybefore adoptiona7f6089
line 655why, one step back655 #[inline]Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c
line 656why, one step back656 #[cold]Merge pull request #185 from dtolnay/fmtDavid Tolnaybefore adoptiona7f6089
line 657why, one step back657 pub fn format_err(args: Arguments) -> Error {Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c
line 658why, one step back658 #[cfg(anyhow_no_fmt_arguments_as_str)]Merge pull request #185 from dtolnay/fmtDavid Tolnaybefore adoptiona7f6089
line 659why, one step back659 let fmt_arguments_as_str = None::<&str>;Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c
line 660why, one step back660 #[cfg(not(anyhow_no_fmt_arguments_as_str))]Merge pull request #184 from dtolnay/escapeDavid Tolnaybefore adoption6c1fd34
line 661why, one step back661 let fmt_arguments_as_str = args.as_str();Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c
line 662why, one step back662Merge pull request #184 from dtolnay/escapeDavid Tolnaybefore adoption6c1fd34
line 663why, one step back663 if let Some(message) = fmt_arguments_as_str {Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c
lines 664–665why, one step back664 // anyhow!("literal"), can downcast to &'static str665 Error::msg(message)Merge pull request #184 from dtolnay/escapeDavid Tolnaybefore adoption6c1fd34
lines 666–668why, one step back666 } else {667 // anyhow!("interpolate {var}"), can downcast to String668 Error::msg(fmt::format(args))Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c
line 669why, one step back669 }Merge pull request #130 from dtolnay/ensureDavid Tolnaybefore adoptioncdfd375
line 670why, one step back670 }Merge pull request #229 from dtolnay/must_useDavid Tolnaybefore adoptionc8a3e42
lines 671–678why, one step back671672 #[doc(hidden)]673 #[inline]674 #[cold]675 #[must_use]676 pub fn must_use(error: Error) -> Error {677 error678 }Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5
line 679why, one step back679}