# anyhow 1.0.104

> [![github]](https://github.com/dtolnay/anyhow)&ensp;[![crates-io]](https://crates.io/crates/anyhow)&ensp;[![docs-rs]](https://docs.rs/anyhow)

## anyhow

[![github]](https://github.com/dtolnay/anyhow)&ensp;[![crates-io]](https://crates.io/crates/anyhow)&ensp;[![docs-rs]](https://docs.rs/anyhow)

[github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
[crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
[docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs

<br>

This library provides [`anyhow::Error`][Error], a trait object based error
type for easy idiomatic error handling in Rust applications.

<br>

### anyhow › Details

- Use `Result<T, anyhow::Error>`, or equivalently `anyhow::Result<T>`, as
  the return type of any fallible function.

  Within the function, use `?` to easily propagate any error that implements
  the [`std::error::Error`] trait.

  ```
  # pub trait Deserialize {}
  #
  # mod serde_json {
  #     use super::Deserialize;
  #     use std::io;
  #
  #     pub fn from_str<T: Deserialize>(json: &str) -> io::Result<T> {
  #         unimplemented!()
  #     }
  # }
  #
  # struct ClusterMap;
  #
  # impl Deserialize for ClusterMap {}
  #
  use anyhow::Result;

  fn get_cluster_info() -> Result<ClusterMap> {
      let config = std::fs::read_to_string("cluster.json")?;
      let map: ClusterMap = serde_json::from_str(&config)?;
      Ok(map)
  }
  #
  # fn main() {}
  ```

- Attach context to help the person troubleshooting the error understand
  where things went wrong. A low-level error like "No such file or
  directory" can be annoying to debug without more context about what higher
  level step the application was in the middle of.

  ```
  # struct It;
  #
  # impl It {
  #     fn detach(&self) -> Result<()> {
  #         unimplemented!()
  #     }
  # }
  #
  use anyhow::{Context, Result};

  fn main() -> Result<()> {
      # return Ok(());
      #
      # const _: &str = stringify! {
      ...
      # };
      #
      # let it = It;
      # let path = "./path/to/instrs.json";
      #
      it.detach().context("Failed to detach the important thing")?;

      let content = std::fs::read(path)
          .with_context(|| format!("Failed to read instrs from {}", path))?;
      #
      # const _: &str = stringify! {
      ...
      # };
      #
      # Ok(())
  }
  ```

  ```console
  Error: Failed to read instrs from ./path/to/instrs.json

  Caused by:
      No such file or directory (os error 2)
  ```

- Downcasting is supported and can be by value, by shared reference, or by
  mutable reference as needed.

  ```
  # use anyhow::anyhow;
  # use std::fmt::{self, Display};
  # use std::task::Poll;
  #
  # #[derive(Debug)]
  # enum DataStoreError {
  #     Censored(()),
  # }
  #
  # impl Display for DataStoreError {
  #     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
  #         unimplemented!()
  #     }
  # }
  #
  # impl std::error::Error for DataStoreError {}
  #
  # const REDACTED_CONTENT: () = ();
  #
  # let error = anyhow!("...");
  # let root_cause = &error;
  #
  # let ret =
  // If the error was caused by redaction, then return a
  // tombstone instead of the content.
  match root_cause.downcast_ref::<DataStoreError>() {
      Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),
      None => Err(error),
  }
  # ;
  ```

- If using Rust &ge; 1.65, a backtrace is captured and printed with the
  error if the underlying error type does not already provide its own. In
  order to see backtraces, they must be enabled through the environment
  variables described in [`std::backtrace`]:

  - If you want panics and errors to both have backtraces, set
    `RUST_BACKTRACE=1`;
  - If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`;
  - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and
    `RUST_LIB_BACKTRACE=0`.

  [`std::backtrace`]: std::backtrace#environment-variables

- Anyhow works with any error type that has an impl of `std::error::Error`,
  including ones defined in your crate. We do not bundle a `derive(Error)`
  macro but you can write the impls yourself or use a standalone macro like
  [thiserror].

  [thiserror]: https://github.com/dtolnay/thiserror

  ```
  use thiserror::Error;

  #[derive(Error, Debug)]
  pub enum FormatError {
      #[error("Invalid header (expected {expected:?}, got {found:?})")]
      InvalidHeader {
          expected: String,
          found: String,
      },
      #[error("Missing attribute: {0}")]
      MissingAttribute(String),
  }
  ```

- One-off error messages can be constructed using the `anyhow!` macro, which
  supports string interpolation and produces an `anyhow::Error`.

  ```
  # use anyhow::{anyhow, Result};
  #
  # fn demo() -> Result<()> {
  #     let missing = "...";
  return Err(anyhow!("Missing attribute: {}", missing));
  #     Ok(())
  # }
  ```

  A `bail!` macro is provided as a shorthand for the same early return.

  ```
  # use anyhow::{bail, Result};
  #
  # fn demo() -> Result<()> {
  #     let missing = "...";
  bail!("Missing attribute: {}", missing);
  #     Ok(())
  # }
  ```

<br>

### anyhow › No-std support

In no_std mode, almost all of the same API is available and works the same
way. To depend on Anyhow in no_std mode, disable our default enabled "std"
feature in Cargo.toml. A global allocator is required.

```toml
[dependencies]
anyhow = { version = "1.0", default-features = false }
```

With versions of Rust older than 1.81, no_std mode may require an additional
`.map_err(Error::msg)` when working with a non-Anyhow error type inside a
function that returns Anyhow's error type, as the trait that `?`-based error
conversions are defined by is only available in std in those old versions.

## anyhow (impl)

```
# type T = ();
#
use anyhow::{Context, Result};

fn maybe_get() -> Option<T> {
    # const IGNORE: &str = stringify! {
    ...
    # };
    # unimplemented!()
}

fn demo() -> Result<()> {
    let t = maybe_get().context("there is no T")?;
    # const IGNORE: &str = stringify! {
    ...
    # };
    # unimplemented!()
}
```

## anyhow::Chain (struct)

Iterator of a chain of source errors.

This type is the iterator returned by [`Error::chain`].

### anyhow::Chain (struct) › Example

```
use anyhow::Error;
use std::io;

pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
    for cause in error.chain() {
        if let Some(io_error) = cause.downcast_ref::<io::Error>() {
            return Some(io_error.kind());
        }
    }
    None
}
```

## anyhow::Context (trait)

Provides the `context` method for `Result`.

This trait is sealed and cannot be implemented for types outside of
`anyhow`.

<br>

### anyhow::Context (trait) › Example

```
use anyhow::{Context, Result};
use std::fs;
use std::path::PathBuf;

pub struct ImportantThing {
    path: PathBuf,
}

impl ImportantThing {
    # const IGNORE: &'static str = stringify! {
    pub fn detach(&mut self) -> Result<()> {...}
    # };
    # fn detach(&mut self) -> Result<()> {
    #     unimplemented!()
    # }
}

pub fn do_it(mut it: ImportantThing) -> Result<Vec<u8>> {
    it.detach().context("Failed to detach the important thing")?;

    let path = &it.path;
    let content = fs::read(path)
        .with_context(|| format!("Failed to read instrs from {}", path.display()))?;

    Ok(content)
}
```

When printed, the outermost context would be printed first and the lower
level underlying causes would be enumerated below.

```console
Error: Failed to read instrs from ./path/to/instrs.json

Caused by:
    No such file or directory (os error 2)
```

Refer to the [Display representations] documentation for other forms in
which this context chain can be rendered.

[Display representations]: Error#display-representations

<br>

### anyhow::Context (trait) › Effect on downcasting

After attaching context of type `C` onto an error of type `E`, the resulting
`anyhow::Error` may be downcast to `C` **or** to `E`.

That is, in codebases that rely on downcasting, Anyhow's context supports
both of the following use cases:

  - **Attaching context whose type is insignificant onto errors whose type
    is used in downcasts.**

    In other error libraries whose context is not designed this way, it can
    be risky to introduce context to existing code because new context might
    break existing working downcasts. In Anyhow, any downcast that worked
    before adding context will continue to work after you add a context, so
    you should freely add human-readable context to errors wherever it would
    be helpful.

    ```
### anyhow::Context (trait) › use anyhow::bail;
### anyhow::Context (trait) › use thiserror::Error;
### anyhow::Context (trait) › #[derive(Error, Debug)]
### anyhow::Context (trait) › #[error("???")]
### anyhow::Context (trait) › struct SuspiciousError;
### anyhow::Context (trait) › fn helper() -> Result<()> {
### anyhow::Context (trait) › bail!(SuspiciousError);
### anyhow::Context (trait) › }
    use anyhow::{Context, Result};

    fn do_it() -> Result<()> {
        helper().context("Failed to complete the work")?;
### anyhow::Context (trait) › const IGNORE: &str = stringify! {
        ...
### anyhow::Context (trait) › };
### anyhow::Context (trait) › unreachable!()
    }

    fn main() {
        let err = do_it().unwrap_err();
        if let Some(e) = err.downcast_ref::<SuspiciousError>() {
            // If helper() returned SuspiciousError, this downcast will
            // correctly succeed even with the context in between.
### anyhow::Context (trait) › return;
        }
### anyhow::Context (trait) › panic!("expected downcast to succeed");
    }
    ```

  - **Attaching context whose type is used in downcasts onto errors whose
    type is insignificant.**

    Some codebases prefer to use machine-readable context to categorize
    lower level errors in a way that will be actionable to higher levels of
    the application.

    ```
### anyhow::Context (trait) › use anyhow::bail;
### anyhow::Context (trait) › use thiserror::Error;
### anyhow::Context (trait) › #[derive(Error, Debug)]
### anyhow::Context (trait) › #[error("???")]
### anyhow::Context (trait) › struct HelperFailed;
### anyhow::Context (trait) › fn helper() -> Result<()> {
### anyhow::Context (trait) › bail!("no such file or directory");
### anyhow::Context (trait) › }
    use anyhow::{Context, Result};

    fn do_it() -> Result<()> {
        helper().context(HelperFailed)?;
### anyhow::Context (trait) › const IGNORE: &str = stringify! {
        ...
### anyhow::Context (trait) › };
### anyhow::Context (trait) › unreachable!()
    }

    fn main() {
        let err = do_it().unwrap_err();
        if let Some(e) = err.downcast_ref::<HelperFailed>() {
            // If helper failed, this downcast will succeed because
            // HelperFailed is the context that has been attached to
            // that error.
### anyhow::Context (trait) › return;
        }
### anyhow::Context (trait) › panic!("expected downcast to succeed");
    }
    ```

## anyhow::Error (struct)

The `Error` type, a wrapper around a dynamic error type.

`Error` works a lot like `Box<dyn std::error::Error>`, but with these
differences:

- `Error` requires that the error is `Send`, `Sync`, and `'static`.
- `Error` guarantees that a backtrace is available, even if the underlying
  error type does not provide one.
- `Error` is represented as a narrow pointer &mdash; exactly one word in
  size instead of two.

<br>

### anyhow::Error (struct) › Display representations

When you print an error object using "{}" or to_string(), only the outermost
underlying error or context is printed, not any of the lower level causes.
This is exactly as if you had called the Display impl of the error from
which you constructed your anyhow::Error.

```console
Failed to read instrs from ./path/to/instrs.json
```

To print causes as well using anyhow's default formatting of causes, use the
alternate selector "{:#}".

```console
Failed to read instrs from ./path/to/instrs.json: No such file or directory (os error 2)
```

The Debug format "{:?}" includes your backtrace if one was captured. Note
that this is the representation you get by default if you return an error
from `fn main` instead of printing it explicitly yourself.

```console
Error: Failed to read instrs from ./path/to/instrs.json

Caused by:
    No such file or directory (os error 2)
```

and if there is a backtrace available:

```console
Error: Failed to read instrs from ./path/to/instrs.json

Caused by:
    No such file or directory (os error 2)

Stack backtrace:
   0: <E as anyhow::context::ext::StdError>::ext_context
             at /git/anyhow/src/backtrace.rs:26
   1: core::result::Result<T,E>::map_err
             at /git/rustc/src/libcore/result.rs:596
   2: anyhow::context::<impl anyhow::Context<T,E> for core::result::Result<T,E>>::with_context
             at /git/anyhow/src/context.rs:58
   3: testing::main
             at src/main.rs:5
   4: std::rt::lang_start
             at /git/rustc/src/libstd/rt.rs:61
   5: main
   6: __libc_start_main
   7: _start
```

To see a conventional struct-style Debug representation, use "{:#?}".

```console
Error {
    context: "Failed to read instrs from ./path/to/instrs.json",
    source: Os {
        code: 2,
        kind: NotFound,
        message: "No such file or directory",
    },
}
```

If none of the built-in representations are appropriate and you would prefer
to render the error and its cause chain yourself, it can be done something
like this:

```
use anyhow::{Context, Result};

fn main() {
    if let Err(err) = try_main() {
        eprintln!("ERROR: {}", err);
        err.chain().skip(1).for_each(|cause| eprintln!("because: {}", cause));
        std::process::exit(1);
    }
}

fn try_main() -> Result<()> {
    # const IGNORE: &str = stringify! {
    ...
    # };
    # Ok(())
}
```

## anyhow::Error::chain (function)

An iterator of the chain of source errors contained by this Error.

This iterator will visit every error in the cause chain of this error
object, beginning with the error that this error object was created
from.

### anyhow::Error::chain (function) › Example

```
use anyhow::Error;
use std::io;

pub fn underlying_io_error_kind(error: &Error) -> Option<io::ErrorKind> {
    for cause in error.chain() {
        if let Some(io_error) = cause.downcast_ref::<io::Error>() {
            return Some(io_error.kind());
        }
    }
    None
}
```

## anyhow::Error::from_boxed (function)

Construct an error object from a type-erased standard library error.

This is mostly useful for interop with other error libraries.

### anyhow::Error::from_boxed (function) › Example

Here is a skeleton of a library that provides its own error abstraction.
The pair of `From` impls provide bidirectional support for `?`
conversion between `Report` and `anyhow::Error`.

```
use std::error::Error as StdError;

pub struct Report {/* ... */}

impl<E> From<E> for Report
where
    E: Into<anyhow::Error>,
    Result<(), E>: anyhow::Context<(), E>,
{
    fn from(error: E) -> Self {
        let anyhow_error: anyhow::Error = error.into();
        let boxed_error: Box<dyn StdError + Send + Sync + 'static> = anyhow_error.into();
        Report::from_boxed(boxed_error)
    }
}

impl From<Report> for anyhow::Error {
    fn from(report: Report) -> Self {
        let boxed_error: Box<dyn StdError + Send + Sync + 'static> = report.into_boxed();
        anyhow::Error::from_boxed(boxed_error)
    }
}

impl Report {
    fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {
        todo!()
    }
    fn into_boxed(self) -> Box<dyn StdError + Send + Sync + 'static> {
        todo!()
    }
}

// Example usage: can use `?` in both directions.
fn a() -> anyhow::Result<()> {
    b()?;
    Ok(())
}
fn b() -> Result<(), Report> {
    a()?;
    Ok(())
}
```

## anyhow::Ok (function)

Equivalent to `Ok::<_, anyhow::Error>(value)`.

This simplifies creation of an `anyhow::Result` in places where type
inference cannot deduce the `E` type of the result &mdash; without needing
to write `Ok::<_, anyhow::Error>(value)`.

One might think that `anyhow::Result::Ok(value)` would work in such cases
but it does not.

```console
error[E0282]: type annotations needed for `std::result::Result<i32, E>`
  --> src/main.rs:11:13
   |
11 |     let _ = anyhow::Result::Ok(1);
   |         -   ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `E` declared on the enum `Result`
   |         |
   |         consider giving this pattern the explicit type `std::result::Result<i32, E>`, where the type parameter `E` is specified
```

## anyhow::Result (type_alias)

`Result<T, Error>`

This is a reasonable return type to use throughout your application but also
for `fn main`; if you do, failures will be printed along with any
[context][Context] and a backtrace if one was captured.

`anyhow::Result` may be used with one *or* two type parameters.

```rust
use anyhow::Result;

# const IGNORE: &str = stringify! {
fn demo1() -> Result<T> {...}
           // ^ equivalent to std::result::Result<T, anyhow::Error>

fn demo2() -> Result<T, OtherError> {...}
           // ^ equivalent to std::result::Result<T, OtherError>
# };
```

### anyhow::Result (type_alias) › Example

```
# pub trait Deserialize {}
#
# mod serde_json {
#     use super::Deserialize;
#     use std::io;
#
#     pub fn from_str<T: Deserialize>(json: &str) -> io::Result<T> {
#         unimplemented!()
#     }
# }
#
# #[derive(Debug)]
# struct ClusterMap;
#
# impl Deserialize for ClusterMap {}
#
use anyhow::Result;

fn main() -> Result<()> {
    # return Ok(());
    let config = std::fs::read_to_string("cluster.json")?;
    let map: ClusterMap = serde_json::from_str(&config)?;
    println!("cluster info: {:#?}", map);
    Ok(())
}
```

## anyhow::anyhow (macro)

Construct an ad-hoc error from a string or existing non-`anyhow` error
value.

This evaluates to an [`Error`][crate::Error]. It can take either just a
string, or a format string with arguments. It also can take any custom type
which implements `Debug` and `Display`.

If called with a single argument whose type implements `std::error::Error`
(in addition to `Debug` and `Display`, which are always required), then that
Error impl's `source` is preserved as the `source` of the resulting
`anyhow::Error`.

### anyhow::anyhow (macro) › Example

```
# type V = ();
#
use anyhow::{anyhow, Result};

fn lookup(key: &str) -> Result<V> {
    if key.len() != 16 {
        return Err(anyhow!("key length must be 16 characters, got {:?}", key));
    }

    // ...
    # Ok(())
}
```

## anyhow::backtrace (function)

Get the backtrace for this Error.

In order for the backtrace to be meaningful, one of the two environment
variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined
and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat
expensive to capture in Rust, so we don't necessarily want to be
capturing them all over the place all the time.

- If you want panics and errors to both have backtraces, set
  `RUST_BACKTRACE=1`;
- If you want only errors to have backtraces, set
  `RUST_LIB_BACKTRACE=1`;
- If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and
  `RUST_LIB_BACKTRACE=0`.

### anyhow::backtrace (function) › Stability

Standard library backtraces are only available when using Rust &ge;
1.65. On older compilers, this function is only available if the crate's
"backtrace" feature is enabled, and will use the `backtrace` crate as
the underlying backtrace implementation. The return type of this
function on old compilers is `&(impl Debug + Display)`.

```toml
[dependencies]
anyhow = { version = "1.0", features = ["backtrace"] }
```

## anyhow::bail (macro)

Return early with an error.

This macro is equivalent to
<code>return Err([anyhow!($args\...)][anyhow!])</code>.

The surrounding function's or closure's return value is required to be
<code>Result&lt;_, [anyhow::Error][crate::Error]&gt;</code>.

[anyhow!]: crate::anyhow

### anyhow::bail (macro) › Example

```
# use anyhow::{bail, Result};
#
# fn has_permission(user: usize, resource: usize) -> bool {
#     true
# }
#
# fn main() -> Result<()> {
#     let user = 0;
#     let resource = 0;
#
if !has_permission(user, resource) {
    bail!("permission denied for accessing {}", resource);
}
#     Ok(())
# }
```

```
# use anyhow::{bail, Result};
# use thiserror::Error;
#
# const MAX_DEPTH: usize = 1;
#
#[derive(Error, Debug)]
enum ScienceError {
    #[error("recursion limit exceeded")]
    RecursionLimitExceeded,
    # #[error("...")]
    # More = (stringify! {
    ...
    # }, 1).1,
}

# fn main() -> Result<()> {
#     let depth = 0;
#
if depth > MAX_DEPTH {
    bail!(ScienceError::RecursionLimitExceeded);
}
#     Ok(())
# }
```

## anyhow::context (function)

Wrap the error value with additional context.

## anyhow::context (function)

Wrap the error value with additional context.

For attaching context to a `Result` as it is propagated, the
[`Context`][crate::Context] extension trait may be more convenient than
this function.

The primary reason to use `error.context(...)` instead of
`result.context(...)` via the `Context` trait would be if the context
needs to depend on some data held by the underlying error:

```
# use std::fmt::{self, Debug, Display};
#
# type T = ();
#
# impl std::error::Error for ParseError {}
# impl Debug for ParseError {
#     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
#         unimplemented!()
#     }
# }
# impl Display for ParseError {
#     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
#         unimplemented!()
#     }
# }
#
use anyhow::Result;
use std::fs::File;
use std::path::Path;

struct ParseError {
    line: usize,
    column: usize,
}

fn parse_impl(file: File) -> Result<T, ParseError> {
    # const IGNORE: &str = stringify! {
    ...
    # };
    # unimplemented!()
}

pub fn parse(path: impl AsRef<Path>) -> Result<T> {
    let file = File::open(&path)?;
    parse_impl(file).map_err(|error| {
        let context = format!(
            "only the first {} lines of {} are valid",
            error.line, path.as_ref().display(),
        );
        anyhow::Error::new(error).context(context)
    })
}
```

## anyhow::downcast (function)

Attempt to downcast the error object to a concrete type.

## anyhow::downcast_mut (function)

Downcast this error object by mutable reference.

## anyhow::downcast_ref (function)

Downcast this error object by reference.

### anyhow::downcast_ref (function) › Example

```
# use anyhow::anyhow;
# use std::fmt::{self, Display};
# use std::task::Poll;
#
# #[derive(Debug)]
# enum DataStoreError {
#     Censored(()),
# }
#
# impl Display for DataStoreError {
#     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
#         unimplemented!()
#     }
# }
#
# impl std::error::Error for DataStoreError {}
#
# const REDACTED_CONTENT: () = ();
#
# let error = anyhow!("...");
# let root_cause = &error;
#
# let ret =
// If the error was caused by redaction, then return a tombstone instead
// of the content.
match root_cause.downcast_ref::<DataStoreError>() {
    Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),
    None => Err(error),
}
# ;
```

## anyhow::ensure (macro)

Return early with an error if a condition is not satisfied.

This macro is equivalent to
<code>if !$cond { return Err([anyhow!($args\...)][anyhow!]); }</code>.

The surrounding function's or closure's return value is required to be
<code>Result&lt;_, [anyhow::Error][crate::Error]&gt;</code>.

Analogously to `assert!`, `ensure!` takes a condition and exits the function
if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`
rather than panicking.

[anyhow!]: crate::anyhow

### anyhow::ensure (macro) › Example

```
# use anyhow::{ensure, Result};
#
# fn main() -> Result<()> {
#     let user = 0;
#
ensure!(user == 0, "only user 0 is allowed");
#     Ok(())
# }
```

```
# use anyhow::{ensure, Result};
# use thiserror::Error;
#
# const MAX_DEPTH: usize = 1;
#
#[derive(Error, Debug)]
enum ScienceError {
    #[error("recursion limit exceeded")]
    RecursionLimitExceeded,
    # #[error("...")]
    # More = (stringify! {
    ...
    # }, 1).1,
}

# fn main() -> Result<()> {
#     let depth = 0;
#
ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);
#     Ok(())
# }
```

## anyhow::into_boxed_dyn_error (function)

Convert to a standard library error trait object.

This is implemented as a cheap pointer cast that does not allocate or
deallocate memory. Like [`anyhow::Error::from_boxed`], it's useful for
interop with other error libraries.

The same conversion is also available as
<code style="display:inline;white-space:normal;">impl From&lt;anyhow::Error&gt;
for Box&lt;dyn Error + Send + Sync + &apos;static&gt;</code>.

If a backtrace was collected during construction of the `anyhow::Error`,
that backtrace remains accessible using the standard library `Error`
trait's provider API, but as a consequence, the resulting boxed error
can no longer be downcast to its original underlying type.

```
#![feature(error_generic_member_access)]

use anyhow::anyhow;
use std::backtrace::Backtrace;
use thiserror::Error;

#[derive(Error, Debug)]
#[error("...")]
struct MyError;

let anyhow_error = anyhow!(MyError);
println!("{}", anyhow_error.backtrace());  // has Backtrace
assert!(anyhow_error.downcast_ref::<MyError>().is_some());  // can downcast

let boxed_dyn_error = anyhow_error.into_boxed_dyn_error();
assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_some());  // has Backtrace
assert!(boxed_dyn_error.downcast_ref::<MyError>().is_none());  // can no longer downcast
```

[`anyhow::Error::from_boxed`]: Self::from_boxed

## anyhow::is (function)

Returns true if `E` is the type held by this error object.

For errors with context, this method returns true if `E` matches the
type of the context `C` **or** the type of the error on which the
context has been attached. For details about the interaction between
context and downcasting, [see here].

[see here]: crate::Context#effect-on-downcasting

## anyhow::msg (function)

Create a new error object from a printable error message.

If the argument implements std::error::Error, prefer `Error::new`
instead which preserves the underlying error's cause chain and
backtrace. If the argument may or may not implement std::error::Error
now or in the future, use `anyhow!(err)` which handles either way
correctly.

`Error::msg("...")` is equivalent to `anyhow!("...")` but occasionally
convenient in places where a function is preferable over a macro, such
as iterator or stream combinators:

```
# mod ffi {
#     pub struct Input;
#     pub struct Output;
#     pub async fn do_some_work(_: Input) -> Result<Output, &'static str> {
#         unimplemented!()
#     }
# }
#
# use ffi::{Input, Output};
#
use anyhow::{Error, Result};
use futures::stream::{Stream, StreamExt, TryStreamExt};

async fn demo<S>(stream: S) -> Result<Vec<Output>>
where
    S: Stream<Item = Input>,
{
    stream
        .then(ffi::do_some_work) // returns Result<Output, &str>
        .map_err(Error::msg)
        .try_collect()
        .await
}
```

## anyhow::new (function)

Create a new error object from any error type.

The error type must be threadsafe and `'static`, so that the `Error`
will be as well.

If the error type does not provide a backtrace, a backtrace will be
created here to ensure that a backtrace exists.

## anyhow::reallocate_into_boxed_dyn_error_without_backtrace (function)

Convert to a standard library error trait object.

Unlike `self.into_boxed_dyn_error()`, this method relocates the
underlying error into a new allocation in order to make it downcastable
to `&E` or `Box<E>` for its original underlying error type. Any
backtrace collected during construction of the `anyhow::Error` is
discarded.

```
#![feature(error_generic_member_access)]

use anyhow::anyhow;
use std::backtrace::Backtrace;
use thiserror::Error;

#[derive(Error, Debug)]
#[error("...")]
struct MyError;

let anyhow_error = anyhow!(MyError);
println!("{}", anyhow_error.backtrace());  // has Backtrace
assert!(anyhow_error.downcast_ref::<MyError>().is_some());  // can downcast

let boxed_dyn_error = anyhow_error.reallocate_into_boxed_dyn_error_without_backtrace();
assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_none());  // Backtrace lost
assert!(boxed_dyn_error.downcast_ref::<MyError>().is_some());  // can downcast to &MyError
assert!(boxed_dyn_error.downcast::<MyError>().is_ok());  // can downcast to Box<MyError>
```

## anyhow::root_cause (function)

The lowest level cause of this error &mdash; this error's cause's
cause's cause etc.

The root cause is the last error in the iterator produced by
[`chain()`][Error::chain].

## anyhow::with_context (function)

Wrap the error value with additional context that is evaluated lazily
only once an error does occur.

