| 1 |
Anyhow ¯\\\_(°ペ)\_/¯ |
| 2 |
========================== |
| 3 |
|
| 4 |
[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/anyhow-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/anyhow) |
| 5 |
[<img alt="crates.io" src="https://img.shields.io/crates/v/anyhow.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/anyhow) |
| 6 |
[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-anyhow-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" height="20">](https://docs.rs/anyhow) |
| 7 |
[<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/dtolnay/anyhow/ci.yml?branch=master&style=for-the-badge" height="20">](https://github.com/dtolnay/anyhow/actions?query=branch%3Amaster) |
| 8 |
|
| 9 |
This library provides [`anyhow::Error`][Error], a trait object based error type |
| 10 |
for easy idiomatic error handling in Rust applications. |
| 11 |
|
| 12 |
[Error]: https://docs.rs/anyhow/1.0/anyhow/struct.Error.html |
| 13 |
|
| 14 |
```toml |
| 15 |
[dependencies] |
| 16 |
anyhow = "1.0" |
| 17 |
``` |
| 18 |
|
| 19 |
*Compiler support: requires rustc 1.39+* |
| 20 |
|
| 21 |
<br> |
| 22 |
|
| 23 |
## Details |
| 24 |
|
| 25 |
- Use `Result<T, anyhow::Error>`, or equivalently `anyhow::Result<T>`, as the |
| 26 |
return type of any fallible function. |
| 27 |
|
| 28 |
Within the function, use `?` to easily propagate any error that implements the |
| 29 |
[`std::error::Error`] trait. |
| 30 |
|
| 31 |
```rust |
| 32 |
use anyhow::Result; |
| 33 |
|
| 34 |
fn get_cluster_info() -> Result<ClusterMap> { |
| 35 |
let config = std::fs::read_to_string("cluster.json")?; |
| 36 |
let map: ClusterMap = serde_json::from_str(&config)?; |
| 37 |
Ok(map) |
| 38 |
} |
| 39 |
``` |
| 40 |
|
| 41 |
[`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html |
| 42 |
|
| 43 |
- Attach context to help the person troubleshooting the error understand where |
| 44 |
things went wrong. A low-level error like "No such file or directory" can be |
| 45 |
annoying to debug without more context about what higher level step the |
| 46 |
application was in the middle of. |
| 47 |
|
| 48 |
```rust |
| 49 |
use anyhow::{Context, Result}; |
| 50 |
|
| 51 |
fn main() -> Result<()> { |
| 52 |
... |
| 53 |
it.detach().context("Failed to detach the important thing")?; |
| 54 |
|
| 55 |
let content = std::fs::read(path) |
| 56 |
.with_context(|| format!("Failed to read instrs from {}", path))?; |
| 57 |
... |
| 58 |
} |
| 59 |
``` |
| 60 |
|
| 61 |
```console |
| 62 |
Error: Failed to read instrs from ./path/to/instrs.json |
| 63 |
|
| 64 |
Caused by: |
| 65 |
No such file or directory (os error 2) |
| 66 |
``` |
| 67 |
|
| 68 |
- Downcasting is supported and can be by value, by shared reference, or by |
| 69 |
mutable reference as needed. |
| 70 |
|
| 71 |
```rust |
| 72 |
// If the error was caused by redaction, then return a |
| 73 |
// tombstone instead of the content. |
| 74 |
match root_cause.downcast_ref::<DataStoreError>() { |
| 75 |
Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)), |
| 76 |
None => Err(error), |
| 77 |
} |
| 78 |
``` |
| 79 |
|
| 80 |
- If using Rust ≥ 1.65, a backtrace is captured and printed with the error if |
| 81 |
the underlying error type does not already provide its own. In order to see |
| 82 |
backtraces, they must be enabled through the environment variables described |
| 83 |
in [`std::backtrace`]: |
| 84 |
|
| 85 |
- If you want panics and errors to both have backtraces, set |
| 86 |
`RUST_BACKTRACE=1`; |
| 87 |
- If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`; |
| 88 |
- If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and |
| 89 |
`RUST_LIB_BACKTRACE=0`. |
| 90 |
|
| 91 |
[`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variables |
| 92 |
|
| 93 |
- Anyhow works with any error type that has an impl of `std::error::Error`, |
| 94 |
including ones defined in your crate. We do not bundle a `derive(Error)` macro |
| 95 |
but you can write the impls yourself or use a standalone macro like |
| 96 |
[thiserror]. |
| 97 |
|
| 98 |
```rust |
| 99 |
use thiserror::Error; |
| 100 |
|
| 101 |
#[derive(Error, Debug)] |
| 102 |
pub enum FormatError { |
| 103 |
#[error("Invalid header (expected {expected:?}, got {found:?})")] |
| 104 |
InvalidHeader { |
| 105 |
expected: String, |
| 106 |
found: String, |
| 107 |
}, |
| 108 |
#[error("Missing attribute: {0}")] |
| 109 |
MissingAttribute(String), |
| 110 |
} |
| 111 |
``` |
| 112 |
|
| 113 |
- One-off error messages can be constructed using the `anyhow!` macro, which |
| 114 |
supports string interpolation and produces an `anyhow::Error`. |
| 115 |
|
| 116 |
```rust |
| 117 |
return Err(anyhow!("Missing attribute: {}", missing)); |
| 118 |
``` |
| 119 |
|
| 120 |
A `bail!` macro is provided as a shorthand for the same early return. |
| 121 |
|
| 122 |
```rust |
| 123 |
bail!("Missing attribute: {}", missing); |
| 124 |
``` |
| 125 |
|
| 126 |
<br> |
| 127 |
|
| 128 |
## No-std support |
| 129 |
|
| 130 |
In no_std mode, almost all of the same API is available and works the same way. |
| 131 |
To depend on Anyhow in no_std mode, disable our default enabled "std" feature in |
| 132 |
Cargo.toml. A global allocator is required. |
| 133 |
|
| 134 |
```toml |
| 135 |
[dependencies] |
| 136 |
anyhow = { version = "1.0", default-features = false } |
| 137 |
``` |
| 138 |
|
| 139 |
With versions of Rust older than 1.81, no_std mode may require an additional |
| 140 |
`.map_err(Error::msg)` when working with a non-Anyhow error type inside a |
| 141 |
function that returns Anyhow's error type, as the trait that `?`-based error |
| 142 |
conversions are defined by is only available in std in those old versions. |
| 143 |
|
| 144 |
<br> |
| 145 |
|
| 146 |
## Comparison to failure |
| 147 |
|
| 148 |
The `anyhow::Error` type works something like `failure::Error`, but unlike |
| 149 |
failure ours is built around the standard library's `std::error::Error` trait |
| 150 |
rather than a separate trait `failure::Fail`. The standard library has adopted |
| 151 |
the necessary improvements for this to be possible as part of [RFC 2504]. |
| 152 |
|
| 153 |
[RFC 2504]: https://github.com/rust-lang/rfcs/blob/master/text/2504-fix-error.md |
| 154 |
|
| 155 |
<br> |
| 156 |
|
| 157 |
## Comparison to thiserror |
| 158 |
|
| 159 |
Use Anyhow if you don't care what error type your functions return, you just |
| 160 |
want it to be easy. This is common in application code. Use [thiserror] if you |
| 161 |
are a library that wants to design your own dedicated error type(s) so that on |
| 162 |
failures the caller gets exactly the information that you choose. |
| 163 |
|
| 164 |
[thiserror]: https://github.com/dtolnay/thiserror |
| 165 |
|
| 166 |
<br> |
| 167 |
|
| 168 |
#### License |
| 169 |
|
| 170 |
<sup> |
| 171 |
Licensed under either of <a href="LICENSE-APACHE">Apache License, Version |
| 172 |
2.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option. |
| 173 |
</sup> |
| 174 |
|
| 175 |
<br> |
| 176 |
|
| 177 |
<sub> |
| 178 |
Unless you explicitly state otherwise, any contribution intentionally submitted |
| 179 |
for inclusion in this crate by you, as defined in the Apache-2.0 license, shall |
| 180 |
be dual licensed as above, without any additional terms or conditions. |
| 181 |
</sub> |