failure_ext/
lib.rs

1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under both the MIT license found in the
5 * LICENSE-MIT file in the root directory of this source tree and the Apache
6 * License, Version 2.0 found in the LICENSE-APACHE file in the root directory
7 * of this source tree.
8 */
9
10#![cfg_attr(fbcode_build, feature(error_generic_member_access))]
11#![deny(warnings, missing_docs, clippy::all, rustdoc::broken_intra_doc_links)]
12
13//! Crate extending functionality of the [`anyhow`] crate
14
15use std::error::Error as StdError;
16use std::fmt;
17use std::fmt::Debug;
18use std::fmt::Display;
19
20use anyhow::Error;
21
22mod slogkv;
23pub use crate::slogkv::cause_workaround as cause;
24pub use crate::slogkv::SlogKVError;
25pub use crate::slogkv::SlogKVErrorKey;
26pub use crate::slogkv::SlogKVErrorWithoutBackTrace;
27
28pub mod prelude {
29    //! A "prelude" of `failure_ext` crate.
30    //!
31    //! This prelude is similar to the standard library's prelude in that you'll
32    //! almost always want to import its entire contents, but unlike the standard
33    //! library's prelude you'll have to do so manually:
34    //!
35    //! ```
36    //! # #![allow(unused)]
37    //! use failure_ext::prelude::*;
38    //! ```
39
40    pub use crate::FutureErrorContext;
41    pub use crate::StreamErrorContext;
42}
43
44#[macro_use]
45mod macros;
46mod context_futures;
47mod context_streams;
48pub use crate::context_futures::FutureErrorContext;
49pub use crate::context_streams::StreamErrorContext;
50
51/// Shallow wrapper struct around [anyhow::Error] with [std::fmt::Display]
52/// implementation that shows the entire chain of errors
53pub struct DisplayChain<'a>(&'a Error);
54
55impl<'a> From<&'a Error> for DisplayChain<'a> {
56    fn from(e: &'a Error) -> Self {
57        DisplayChain(e)
58    }
59}
60
61impl Display for DisplayChain<'_> {
62    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
63        let e = self.0;
64        writeln!(fmt, "Error: {e}")?;
65        for c in e.chain().skip(1) {
66            writeln!(fmt, "Caused by: {c}")?;
67        }
68        Ok(())
69    }
70}
71
72/// Temporary immitation of `failure::Compat<T>` to ease migration.
73pub struct Compat<T>(pub T);
74
75impl StdError for Compat<Error> {
76    fn source(&self) -> Option<&(dyn StdError + 'static)> {
77        self.0.source()
78    }
79
80    #[cfg(fbcode_build)]
81    fn provide<'a>(&'a self, request: &mut std::error::Request<'a>) {
82        request.provide_ref::<std::backtrace::Backtrace>(self.0.backtrace());
83    }
84}
85
86impl Display for Compat<Error> {
87    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
88        Display::fmt(&self.0, formatter)
89    }
90}
91
92impl Debug for Compat<Error> {
93    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
94        Debug::fmt(&self.0, formatter)
95    }
96}