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

The walk stopped after 200 commits: lines older than 27fcdd4 point at it.

Add crosslink icons to top of rustdocDavid Tolnaybefore adoption16f607e

lines 1–8why, one step back
1//! [![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//!

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 9–72why, one step back
9//! This library provides [`anyhow::Error`][Error], a trait object based error
10//! 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;

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 73why, one step back
73//! # let path = "./path/to/instrs.json";

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 74why, one step back
74//! #

Capitalize example error messagesDavid Tolnaybefore adoption437c691

line 75why, one step back
75//! it.detach().context("Failed to detach the important thing")?;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 76–77why, one step back
76//!
77//! let content = std::fs::read(path)

Capitalize example error messagesDavid Tolnaybefore adoption437c691

line 78why, one step back
78//! .with_context(|| format!("Failed to read instrs from {}", path))?;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 79–88why, one step back
79//! #
80//! # const _: &str = stringify! {81//! ...82//! # };83//! #84//! # Ok(())85//! }86//! ```87//!88//! ```console

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 89why, one step back
89//! Error: Failed to read instrs from ./path/to/instrs.json

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 90–130why, one step back
90//!
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 back
131//! - If using the nightly channel, or stable with `features = ["backtrace"]`, a
132//! 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 back
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//!

Rephrase nightly backtrace noteDavid Tolnaybefore adoptione46df9f

line 143why, one step back
143//! 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 back
144//!

Merge pull request #70 from dtolnay/envDavid Tolnaybefore adoption8d2acea

line 145why, one step back
145//! [`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variables

Rephrase nightly backtrace noteDavid Tolnaybefore adoptione46df9f

line 146why, one step back
146//! [rust-lang/rust#53487]: https://github.com/rust-lang/rust/issues/53487

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 147–159why, one step back
147//!
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 {

Capitalize example error messagesDavid Tolnaybefore adoption437c691

line 160why, one step back
160//! #[error("Invalid header (expected {expected:?}, got {found:?})")]

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 161–164why, one step back
161//! InvalidHeader {
162//! expected: String,163//! found: String,164//! },

Capitalize example error messagesDavid Tolnaybefore adoption437c691

line 165why, one step back
165//! #[error("Missing attribute: {0}")]

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 166–177why, one step back
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 = "...";

Capitalize example error messagesDavid Tolnaybefore adoption437c691

line 178why, one step back
178//! return Err(anyhow!("Missing attribute: {}", missing));

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 179–181why, one step back
179//! # Ok(())
180//! # }181//! ```

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 182why, one step back
182//!

Copy bail mention from readme to rustdocDavid Tolnaybefore adoptionc25be95

lines 183–194why, one step back
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//!

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

lines 195–211why, one step back
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.

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 212why, one step back
212

Release 1.0.49David Tolnaybefore adoptiona5a98e0

line 213why, one step back
213#![doc(html_root_url = "https://docs.rs/anyhow/1.0.49")]

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 214why, one step back
214#![cfg_attr(backtrace, feature(backtrace))]

Merge pull request #78 from dtolnay/cfgDavid Tolnaybefore adoptione2eb1f5

line 215why, one step back
215#![cfg_attr(doc_cfg, feature(doc_cfg))]

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 216why, one step back
216#![cfg_attr(not(feature = "std"), no_std)]

Catch some warnings in addr_of-related codepathsDavid Tolnaybefore adoption827bb9d

line 217why, one step back
217#![deny(dead_code, unused_imports, unused_mut)]

Disable needless_doctest_main lintDavid Tolnaybefore adoption5e04e77

line 218why, one step back
218#![allow(

Opt in to pedantic clippy lintsDavid Tolnaybefore adoption318db92

lines 219–221why, one step back
219 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 back
222 clippy::missing_panics_doc,

Opt in to pedantic clippy lintsDavid Tolnaybefore adoption318db92

lines 223–224why, one step back
223 clippy::module_name_repetitions,
224 clippy::must_use_candidate,

Disable needless_doctest_main lintDavid Tolnaybefore adoption5e04e77

lines 225–226why, one step back
225 clippy::needless_doctest_main,
226 clippy::new_ret_no_self,

Ignore redundant_else pedantic clippy lintDavid Tolnaybefore adoption2987c9b

line 227why, one step back
227 clippy::redundant_else,

Opt in to pedantic clippy lintsDavid Tolnaybefore adoption318db92

lines 228–230why, one step back
228 clippy::unused_self,
229 clippy::used_underscore_binding,230 clippy::wildcard_imports,

Disable needless_doctest_main lintDavid Tolnaybefore adoption5e04e77

lines 231–232why, one step back
231 clippy::wrong_self_convention
232)]

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 233why, one step back
233

Merge pull request #178 from dtolnay/upDavid Tolnaybefore adoption3c586dd

line 234why, one step back
234extern crate alloc;

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 235why, one step back
235

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 236–237why, one step back
236#[macro_use]
237mod backtrace;

Merge pull request #45 from dtolnay/chainDavid Tolnaybefore adoption00545d5

line 238why, one step back
238mod chain;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 239why, one step back
239mod context;

Merge pull request #193 from dtolnay/ensureDavid Tolnaybefore adoptione05df5f

line 240why, one step back
240mod ensure;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 241why, one step back
241mod error;

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

line 242why, one step back
242mod fmt;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 243why, one step back
243mod kind;

Move macros to their own moduleDavid Tolnaybefore adoption7ce0a30

line 244why, one step back
244mod macros;

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 245why, one step back
245mod ptr;

Move transparent wrapper errors to own moduleDavid Tolnaybefore adoptionba0b307

line 246why, one step back
246mod wrapper;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 247why, one step back
247

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 248why, one step back
248use crate::error::ErrorImpl;

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 249why, one step back
249use crate::ptr::Own;

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

lines 250–251why, one step back
250use core::fmt::Display;
251

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 252why, one step back
252#[cfg(not(feature = "std"))]

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 253why, one step back
253use core::fmt::Debug;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 254why, one step back
254

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

lines 255–256why, one step back
255#[cfg(feature = "std")]
256use std::error::Error as StdError;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 257why, one step back
257

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

lines 258–264why, one step back
258#[cfg(not(feature = "std"))]
259trait StdError: Debug + Display {260 fn source(&self) -> Option<&(dyn StdError + 'static)> {261 None262 }263}264

Merge pull request #38 from dtolnay/format_errDavid Tolnaybefore adoptiond695999

lines 265–266why, one step back
265pub use anyhow as format_err;
266

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 267–276why, one step back
267/// 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.

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

lines 277–287why, one step back
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/// ```console

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 288why, one step back
288/// Failed to read instrs from ./path/to/instrs.json

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

lines 289–294why, one step back
289/// ```
290///291/// To print causes as well using anyhow's default formatting of causes, use the292/// alternate selector "{:#}".293///294/// ```console

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 295why, one step back
295/// Failed to read instrs from ./path/to/instrs.json: No such file or directory (os error 2)

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

lines 296–302why, one step back
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/// ```console

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 303why, one step back
303/// Error: Failed to read instrs from ./path/to/instrs.json

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

lines 304–306why, one step back
304///
305/// Caused by:306/// No such file or directory (os error 2)

Show an example of {:?} without backtraceDavid Tolnaybefore adoptionf7424bd

lines 307–315why, one step back
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)

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

lines 316–336why, one step back
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 {

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 337why, one step back
337/// context: "Failed to read instrs from ./path/to/instrs.json",

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

lines 338–367why, one step back
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/// ```

Merge pull request 132 from dtolnay/reprDavid Tolnaybefore adoption0650f43

line 368why, one step back
368#[repr(transparent)]

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 369why, one step back
369pub struct Error {

Adopt some NonNull wrappersDavid Tolnaybefore adoption62673e2

line 370why, one step back
370 inner: Own<ErrorImpl>,

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 371–391why, one step back
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/// ```

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 392why, one step back
392#[cfg(feature = "std")]

Merge pull request #128 from dtolnay/doc-cfgDavid Tolnaybefore adoption0c0e41f

line 393why, one step back
393#[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]

Merge pull request #42 from dtolnay/fmtDavid Tolnaybefore adoption74954bd

line 394why, one step back
394#[derive(Clone)]

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 395why, one step back
395pub struct Chain<'a> {

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 396why, one step back
396 state: crate::chain::ChainState<'a>,

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 397–447why, one step back
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/// ```

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 448why, one step back
448pub type Result<T, E = Error> = core::result::Result<T, E>;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 449–454why, one step back
449
450/// Provides the `context` method for `Result`.451///452/// This trait is sealed and cannot be implemented for types outside of453/// `anyhow`.454///

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 455–456why, one step back
455/// <br>
456///

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 457–477why, one step back
457/// # Example
458///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>> {

Capitalize example error messagesDavid Tolnaybefore adoption437c691

line 478why, one step back
478/// it.detach().context("Failed to detach the important thing")?;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 479–481why, one step back
479///
480/// let path = &it.path;481/// let content = fs::read(path)

Capitalize example error messagesDavid Tolnaybefore adoption437c691

line 482why, one step back
482/// .with_context(|| format!("Failed to read instrs from {}", path.display()))?;

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 483–491why, one step back
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/// ```console

Use instrs.json as file path in examplesDavid Tolnaybefore adoption87e85ab

line 492why, one step back
492/// Error: Failed to read instrs from ./path/to/instrs.json

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 493why, one step back
493///

Match actual capitalization in Context example outputDavid Tolnaybefore adoptiondef64cb

line 494why, one step back
494/// Caused by:

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 495–496why, one step back
495/// No such file or directory (os error 2)
496/// ```

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 497–532why, one step back
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<()> {

Capitalize example error messagesDavid Tolnaybefore adoption437c691

line 533why, one step back
533/// helper().context("Failed to complete the work")?;

Merge pull request #34 from dtolnay/contextDavid Tolnaybefore adoption8fcd8d0

lines 534–590why, one step back
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/// ```

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 591–604why, one step back
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}604

Add anyhow::OkDavid Tolnaybefore adoption2d4bb64

lines 605–628why, one step back
605/// 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}628

Move macros to their own moduleDavid Tolnaybefore adoption7ce0a30

line 629why, one step back
629// Not public API. Referenced by macro-generated code.

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

lines 630–631why, one step back
630#[doc(hidden)]
631pub mod private {

Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c

lines 632–633why, one step back
632 use crate::Error;
633 use alloc::fmt;

Merge pull request #185 from dtolnay/fmtDavid Tolnaybefore adoptiona7f6089

line 634why, one step back
634 use core::fmt::Arguments;

Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c

line 635why, one step back
635

Merge pull request #193 from dtolnay/ensureDavid Tolnaybefore adoptione05df5f

line 636why, one step back
636 pub use crate::ensure::{BothDebug, NotBothDebug};

Merge pull request #179 from dtolnay/upDavid Tolnaybefore adoptioncd03064

line 637why, one step back
637 pub use alloc::format;

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 638why, one step back
638 pub use core::result::Result::Err;

Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c

line 639why, one step back
639 pub use core::{concat, format_args, stringify};

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

line 640why, one step back
640

Remove need for allow(unused_imports)David Tolnaybefore adoption4f123ae

lines 641–642why, one step back
641 #[doc(hidden)]
642 pub mod kind {

Merge pull request #53 from dtolnay/nostdDavid Tolnaybefore adoption55343b9

lines 643–646why, one step back
643 pub use crate::kind::{AdhocKind, TraitKind};
644645 #[cfg(feature = "std")]646 pub use crate::kind::BoxedKind;

Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c

lines 647–649why, one step back
647 }
648649 #[doc(hidden)]

Merge pull request #185 from dtolnay/fmtDavid Tolnaybefore adoptiona7f6089

line 650why, one step back
650 #[inline]

Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c

line 651why, one step back
651 #[cold]

Merge pull request #185 from dtolnay/fmtDavid Tolnaybefore adoptiona7f6089

line 652why, one step back
652 pub fn format_err(args: Arguments) -> Error {

Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c

line 653why, one step back
653 #[cfg(anyhow_no_fmt_arguments_as_str)]

Merge pull request #185 from dtolnay/fmtDavid Tolnaybefore adoptiona7f6089

line 654why, one step back
654 let fmt_arguments_as_str = None::<&str>;

Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c

line 655why, one step back
655 #[cfg(not(anyhow_no_fmt_arguments_as_str))]

Merge pull request #184 from dtolnay/escapeDavid Tolnaybefore adoption6c1fd34

line 656why, one step back
656 let fmt_arguments_as_str = args.as_str();

Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c

line 657why, one step back
657

Merge pull request #184 from dtolnay/escapeDavid Tolnaybefore adoption6c1fd34

line 658why, one step back
658 if let Some(message) = fmt_arguments_as_str {

Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c

lines 659–660why, one step back
659 // anyhow!("literal"), can downcast to &'static str
660 Error::msg(message)

Merge pull request #184 from dtolnay/escapeDavid Tolnaybefore adoption6c1fd34

lines 661–663why, one step back
661 } else {
662 // anyhow!("interpolate {var}"), can downcast to String663 Error::msg(fmt::format(args))

Merge pull request #180 from dtolnay/captureDavid Tolnaybefore adoption8546f4c

line 664why, one step back
664 }

Merge pull request #130 from dtolnay/ensureDavid Tolnaybefore adoptioncdfd375

line 665why, one step back
665 }

Also move Error and Chain to get usable paths in diagnosticsDavid Tolnaybefore adoption27fcdd4

line 666why, one step back
666}