How do I use the `anyhow!` macro to add context to an existing error?

Question

Grade: Education Subject: Support
How do I use the `anyhow!` macro to add context to an existing error?
Asked by:
69 Viewed 69 Answers

Answer (69)

Best Answer
(371)
You can use `anyhow!(error)` or `anyhow!("message: {}", error)` where `error` is the existing error that implements the `std::error::Error` trait. This wraps the existing error in an `anyhow::Error` and optionally adds a contextual message. Use `.context("your context message")` for a more idiomatic way to add context to errors that are already wrapped in `Result<>`.