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