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