anyhow/
lib.rs

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=github
4//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
5//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
6//!
7//! <br>
8//!
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//! # Details
15//!
16//! - Use `Result<T, anyhow::Error>`, or equivalently `anyhow::Result<T>`, as
17//!   the return type of any fallible function.
18//!
19//!   Within the function, use `?` to easily propagate any error that implements
20//!   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 understand
50//!   where things went wrong. A low-level error like "No such file or
51//!   directory" can be annoying to debug without more context about what higher
52//!   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//!   ```console
89//!   Error: Failed to read instrs from ./path/to/instrs.json
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 by
96//!   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 a
123//!   // 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 the
132//!   error if the underlying error type does not already provide its own. In
133//!   order to see backtraces, they must be enabled through the environment
134//!   variables described in [`std::backtrace`]:
135//!
136//!   - If you want panics and errors to both have backtraces, set
137//!     `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` and
140//!     `RUST_LIB_BACKTRACE=0`.
141//!
142//!   [`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variables
143//!
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 like
147//!   [thiserror].
148//!
149//!   [thiserror]: https://github.com/dtolnay/thiserror
150//!
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, which
167//!   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 support
194//!
195//! In no_std mode, almost all of the same API is available and works the same
196//! 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//! ```toml
200//! [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 additional
205//! `.map_err(Error::msg)` when working with a non-Anyhow error type inside a
206//! function that returns Anyhow's error type, as the trait that `?`-based error
207//! conversions are defined by is only available in std in those old versions.
208
209#![doc(html_root_url = "https://docs.rs/anyhow/1.0.89")]
210#![cfg_attr(error_generic_member_access, feature(error_generic_member_access))]
211#![no_std]
212#![deny(dead_code, unused_imports, unused_mut)]
213#![cfg_attr(
214    not(anyhow_no_unsafe_op_in_unsafe_fn_lint),
215    deny(unsafe_op_in_unsafe_fn)
216)]
217#![cfg_attr(anyhow_no_unsafe_op_in_unsafe_fn_lint, allow(unused_unsafe))]
218#![allow(
219    clippy::doc_markdown,
220    clippy::enum_glob_use,
221    clippy::explicit_auto_deref,
222    clippy::extra_unused_type_parameters,
223    clippy::incompatible_msrv,
224    clippy::let_underscore_untyped,
225    clippy::missing_errors_doc,
226    clippy::missing_panics_doc,
227    clippy::module_name_repetitions,
228    clippy::must_use_candidate,
229    clippy::needless_doctest_main,
230    clippy::new_ret_no_self,
231    clippy::redundant_else,
232    clippy::return_self_not_must_use,
233    clippy::struct_field_names,
234    clippy::unused_self,
235    clippy::used_underscore_binding,
236    clippy::wildcard_imports,
237    clippy::wrong_self_convention
238)]
239
240#[cfg(all(
241    anyhow_nightly_testing,
242    feature = "std",
243    not(error_generic_member_access)
244))]
245compile_error!("Build script probe failed to compile.");
246
247extern crate alloc;
248
249#[cfg(feature = "std")]
250extern crate std;
251
252#[macro_use]
253mod backtrace;
254mod chain;
255mod context;
256mod ensure;
257mod error;
258mod fmt;
259mod kind;
260mod macros;
261mod ptr;
262mod wrapper;
263
264use crate::error::ErrorImpl;
265use crate::ptr::Own;
266use core::fmt::Display;
267
268#[cfg(all(not(feature = "std"), anyhow_no_core_error))]
269use core::fmt::Debug;
270
271#[cfg(feature = "std")]
272use std::error::Error as StdError;
273
274#[cfg(not(any(feature = "std", anyhow_no_core_error)))]
275use core::error::Error as StdError;
276
277#[cfg(all(not(feature = "std"), anyhow_no_core_error))]
278trait StdError: Debug + Display {
279    fn source(&self) -> Option<&(dyn StdError + 'static)> {
280        None
281    }
282}
283
284#[doc(no_inline)]
285pub use anyhow as format_err;
286
287/// The `Error` type, a wrapper around a dynamic error type.
288///
289/// `Error` works a lot like `Box<dyn std::error::Error>`, but with these
290/// differences:
291///
292/// - `Error` requires that the error is `Send`, `Sync`, and `'static`.
293/// - `Error` guarantees that a backtrace is available, even if the underlying
294///   error type does not provide one.
295/// - `Error` is represented as a narrow pointer &mdash; exactly one word in
296///   size instead of two.
297///
298/// <br>
299///
300/// # Display representations
301///
302/// When you print an error object using "{}" or to_string(), only the outermost
303/// underlying error or context is printed, not any of the lower level causes.
304/// This is exactly as if you had called the Display impl of the error from
305/// which you constructed your anyhow::Error.
306///
307/// ```console
308/// Failed to read instrs from ./path/to/instrs.json
309/// ```
310///
311/// To print causes as well using anyhow's default formatting of causes, use the
312/// alternate selector "{:#}".
313///
314/// ```console
315/// Failed to read instrs from ./path/to/instrs.json: No such file or directory (os error 2)
316/// ```
317///
318/// The Debug format "{:?}" includes your backtrace if one was captured. Note
319/// that this is the representation you get by default if you return an error
320/// from `fn main` instead of printing it explicitly yourself.
321///
322/// ```console
323/// Error: Failed to read instrs from ./path/to/instrs.json
324///
325/// Caused by:
326///     No such file or directory (os error 2)
327/// ```
328///
329/// and if there is a backtrace available:
330///
331/// ```console
332/// Error: Failed to read instrs from ./path/to/instrs.json
333///
334/// Caused by:
335///     No such file or directory (os error 2)
336///
337/// Stack backtrace:
338///    0: <E as anyhow::context::ext::StdError>::ext_context
339///              at /git/anyhow/src/backtrace.rs:26
340///    1: core::result::Result<T,E>::map_err
341///              at /git/rustc/src/libcore/result.rs:596
342///    2: anyhow::context::<impl anyhow::Context<T,E> for core::result::Result<T,E>>::with_context
343///              at /git/anyhow/src/context.rs:58
344///    3: testing::main
345///              at src/main.rs:5
346///    4: std::rt::lang_start
347///              at /git/rustc/src/libstd/rt.rs:61
348///    5: main
349///    6: __libc_start_main
350///    7: _start
351/// ```
352///
353/// To see a conventional struct-style Debug representation, use "{:#?}".
354///
355/// ```console
356/// Error {
357///     context: "Failed to read instrs from ./path/to/instrs.json",
358///     source: Os {
359///         code: 2,
360///         kind: NotFound,
361///         message: "No such file or directory",
362///     },
363/// }
364/// ```
365///
366/// If none of the built-in representations are appropriate and you would prefer
367/// to render the error and its cause chain yourself, it can be done something
368/// like this:
369///
370/// ```
371/// use anyhow::{Context, Result};
372///
373/// fn main() {
374///     if let Err(err) = try_main() {
375///         eprintln!("ERROR: {}", err);
376///         err.chain().skip(1).for_each(|cause| eprintln!("because: {}", cause));
377///         std::process::exit(1);
378///     }
379/// }
380///
381/// fn try_main() -> Result<()> {
382///     # const IGNORE: &str = stringify! {
383///     ...
384///     # };
385///     # Ok(())
386/// }
387/// ```
388#[repr(transparent)]
389pub struct Error {
390    inner: Own<ErrorImpl>,
391}
392
393/// Iterator of a chain of source errors.
394///
395/// This type is the iterator returned by [`Error::chain`].
396///
397/// # Example
398///
399/// ```
400/// use anyhow::Error;
401/// use std::io;
402///
403/// pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
404///     for cause in error.chain() {
405///         if let Some(io_error) = cause.downcast_ref::<io::Error>() {
406///             return Some(io_error.kind());
407///         }
408///     }
409///     None
410/// }
411/// ```
412#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
413#[derive(Clone)]
414pub struct Chain<'a> {
415    state: crate::chain::ChainState<'a>,
416}
417
418/// `Result<T, Error>`
419///
420/// This is a reasonable return type to use throughout your application but also
421/// for `fn main`; if you do, failures will be printed along with any
422/// [context][Context] and a backtrace if one was captured.
423///
424/// `anyhow::Result` may be used with one *or* two type parameters.
425///
426/// ```rust
427/// use anyhow::Result;
428///
429/// # const IGNORE: &str = stringify! {
430/// fn demo1() -> Result<T> {...}
431///            // ^ equivalent to std::result::Result<T, anyhow::Error>
432///
433/// fn demo2() -> Result<T, OtherError> {...}
434///            // ^ equivalent to std::result::Result<T, OtherError>
435/// # };
436/// ```
437///
438/// # Example
439///
440/// ```
441/// # pub trait Deserialize {}
442/// #
443/// # mod serde_json {
444/// #     use super::Deserialize;
445/// #     use std::io;
446/// #
447/// #     pub fn from_str<T: Deserialize>(json: &str) -> io::Result<T> {
448/// #         unimplemented!()
449/// #     }
450/// # }
451/// #
452/// # #[derive(Debug)]
453/// # struct ClusterMap;
454/// #
455/// # impl Deserialize for ClusterMap {}
456/// #
457/// use anyhow::Result;
458///
459/// fn main() -> Result<()> {
460///     # return Ok(());
461///     let config = std::fs::read_to_string("cluster.json")?;
462///     let map: ClusterMap = serde_json::from_str(&config)?;
463///     println!("cluster info: {:#?}", map);
464///     Ok(())
465/// }
466/// ```
467pub type Result<T, E = Error> = core::result::Result<T, E>;
468
469/// Provides the `context` method for `Result`.
470///
471/// This trait is sealed and cannot be implemented for types outside of
472/// `anyhow`.
473///
474/// <br>
475///
476/// # Example
477///
478/// ```
479/// use anyhow::{Context, Result};
480/// use std::fs;
481/// use std::path::PathBuf;
482///
483/// pub struct ImportantThing {
484///     path: PathBuf,
485/// }
486///
487/// impl ImportantThing {
488///     # const IGNORE: &'static str = stringify! {
489///     pub fn detach(&mut self) -> Result<()> {...}
490///     # };
491///     # fn detach(&mut self) -> Result<()> {
492///     #     unimplemented!()
493///     # }
494/// }
495///
496/// pub fn do_it(mut it: ImportantThing) -> Result<Vec<u8>> {
497///     it.detach().context("Failed to detach the important thing")?;
498///
499///     let path = &it.path;
500///     let content = fs::read(path)
501///         .with_context(|| format!("Failed to read instrs from {}", path.display()))?;
502///
503///     Ok(content)
504/// }
505/// ```
506///
507/// When printed, the outermost context would be printed first and the lower
508/// level underlying causes would be enumerated below.
509///
510/// ```console
511/// Error: Failed to read instrs from ./path/to/instrs.json
512///
513/// Caused by:
514///     No such file or directory (os error 2)
515/// ```
516///
517/// Refer to the [Display representations] documentation for other forms in
518/// which this context chain can be rendered.
519///
520/// [Display representations]: Error#display-representations
521///
522/// <br>
523///
524/// # Effect on downcasting
525///
526/// After attaching context of type `C` onto an error of type `E`, the resulting
527/// `anyhow::Error` may be downcast to `C` **or** to `E`.
528///
529/// That is, in codebases that rely on downcasting, Anyhow's context supports
530/// both of the following use cases:
531///
532///   - **Attaching context whose type is insignificant onto errors whose type
533///     is used in downcasts.**
534///
535///     In other error libraries whose context is not designed this way, it can
536///     be risky to introduce context to existing code because new context might
537///     break existing working downcasts. In Anyhow, any downcast that worked
538///     before adding context will continue to work after you add a context, so
539///     you should freely add human-readable context to errors wherever it would
540///     be helpful.
541///
542///     ```
543///     # use anyhow::bail;
544///     # use thiserror::Error;
545///     #
546///     # #[derive(Error, Debug)]
547///     # #[error("???")]
548///     # struct SuspiciousError;
549///     #
550///     # fn helper() -> Result<()> {
551///     #     bail!(SuspiciousError);
552///     # }
553///     #
554///     use anyhow::{Context, Result};
555///
556///     fn do_it() -> Result<()> {
557///         helper().context("Failed to complete the work")?;
558///         # const IGNORE: &str = stringify! {
559///         ...
560///         # };
561///         # unreachable!()
562///     }
563///
564///     fn main() {
565///         let err = do_it().unwrap_err();
566///         if let Some(e) = err.downcast_ref::<SuspiciousError>() {
567///             // If helper() returned SuspiciousError, this downcast will
568///             // correctly succeed even with the context in between.
569///             # return;
570///         }
571///         # panic!("expected downcast to succeed");
572///     }
573///     ```
574///
575///   - **Attaching context whose type is used in downcasts onto errors whose
576///     type is insignificant.**
577///
578///     Some codebases prefer to use machine-readable context to categorize
579///     lower level errors in a way that will be actionable to higher levels of
580///     the application.
581///
582///     ```
583///     # use anyhow::bail;
584///     # use thiserror::Error;
585///     #
586///     # #[derive(Error, Debug)]
587///     # #[error("???")]
588///     # struct HelperFailed;
589///     #
590///     # fn helper() -> Result<()> {
591///     #     bail!("no such file or directory");
592///     # }
593///     #
594///     use anyhow::{Context, Result};
595///
596///     fn do_it() -> Result<()> {
597///         helper().context(HelperFailed)?;
598///         # const IGNORE: &str = stringify! {
599///         ...
600///         # };
601///         # unreachable!()
602///     }
603///
604///     fn main() {
605///         let err = do_it().unwrap_err();
606///         if let Some(e) = err.downcast_ref::<HelperFailed>() {
607///             // If helper failed, this downcast will succeed because
608///             // HelperFailed is the context that has been attached to
609///             // that error.
610///             # return;
611///         }
612///         # panic!("expected downcast to succeed");
613///     }
614///     ```
615pub trait Context<T, E>: context::private::Sealed {
616    /// Wrap the error value with additional context.
617    fn context<C>(self, context: C) -> Result<T, Error>
618    where
619        C: Display + Send + Sync + 'static;
620
621    /// Wrap the error value with additional context that is evaluated lazily
622    /// only once an error does occur.
623    fn with_context<C, F>(self, f: F) -> Result<T, Error>
624    where
625        C: Display + Send + Sync + 'static,
626        F: FnOnce() -> C;
627}
628
629/// Equivalent to Ok::<_, anyhow::Error>(value).
630///
631/// This simplifies creation of an anyhow::Result in places where type inference
632/// cannot deduce the `E` type of the result &mdash; without needing to write
633/// `Ok::<_, anyhow::Error>(value)`.
634///
635/// One might think that `anyhow::Result::Ok(value)` would work in such cases
636/// but it does not.
637///
638/// ```console
639/// error[E0282]: type annotations needed for `std::result::Result<i32, E>`
640///   --> src/main.rs:11:13
641///    |
642/// 11 |     let _ = anyhow::Result::Ok(1);
643///    |         -   ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `E` declared on the enum `Result`
644///    |         |
645///    |         consider giving this pattern the explicit type `std::result::Result<i32, E>`, where the type parameter `E` is specified
646/// ```
647#[allow(non_snake_case)]
648pub fn Ok<T>(t: T) -> Result<T> {
649    Result::Ok(t)
650}
651
652// Not public API. Referenced by macro-generated code.
653#[doc(hidden)]
654pub mod __private {
655    use self::not::Bool;
656    use crate::Error;
657    use alloc::fmt;
658    use core::fmt::Arguments;
659
660    #[doc(hidden)]
661    pub use crate::ensure::{BothDebug, NotBothDebug};
662    #[doc(hidden)]
663    pub use alloc::format;
664    #[doc(hidden)]
665    pub use core::result::Result::Err;
666    #[doc(hidden)]
667    pub use core::{concat, format_args, stringify};
668
669    #[doc(hidden)]
670    pub mod kind {
671        #[doc(hidden)]
672        pub use crate::kind::{AdhocKind, TraitKind};
673
674        #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
675        #[doc(hidden)]
676        pub use crate::kind::BoxedKind;
677    }
678
679    #[doc(hidden)]
680    #[inline]
681    #[cold]
682    pub fn format_err(args: Arguments) -> Error {
683        #[cfg(anyhow_no_fmt_arguments_as_str)]
684        let fmt_arguments_as_str = None::<&str>;
685        #[cfg(not(anyhow_no_fmt_arguments_as_str))]
686        let fmt_arguments_as_str = args.as_str();
687
688        if let Some(message) = fmt_arguments_as_str {
689            // anyhow!("literal"), can downcast to &'static str
690            Error::msg(message)
691        } else {
692            // anyhow!("interpolate {var}"), can downcast to String
693            Error::msg(fmt::format(args))
694        }
695    }
696
697    #[doc(hidden)]
698    #[inline]
699    #[cold]
700    #[must_use]
701    pub fn must_use(error: Error) -> Error {
702        error
703    }
704
705    #[doc(hidden)]
706    #[inline]
707    pub fn not(cond: impl Bool) -> bool {
708        cond.not()
709    }
710
711    mod not {
712        #[doc(hidden)]
713        pub trait Bool {
714            fn not(self) -> bool;
715        }
716
717        impl Bool for bool {
718            #[inline]
719            fn not(self) -> bool {
720                !self
721            }
722        }
723
724        impl Bool for &bool {
725            #[inline]
726            fn not(self) -> bool {
727                !*self
728            }
729        }
730    }
731}