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