README.md
This file
Path
README.md
179 lines · 5.9 KiB · Markdown
Last changed by
Remove rustc version requirement from readmeDavid Tolnaybefore adoption0d82268
History of this fileTake it
The walk stopped after 200 commits: lines older than 553ed38 point at it.
Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 1–26why, one step back1Anyhow ¯\\\_(°ペ)\_/¯2==========================34[<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)89This library provides [`anyhow::Error`][Error], a trait object based error type10for easy idiomatic error handling in Rust applications.1112[Error]: https://docs.rs/anyhow/1.0/anyhow/struct.Error.html1314```toml15[dependencies]16anyhow = "1.0"17```1819<br>2021## Details2223- Use `Result<T, anyhow::Error>`, or equivalently `anyhow::Result<T>`, as the24 return type of any fallible function.2526 Within the function, use `?` to easily propagate any error that implements theMerge pull request #343 from Arthur-Milchior/readme1David Tolnaybefore adoptionf01080b
line 27why, one step back27 [`std::error::Error`] trait.Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 28–38why, one step back2829 ```rust30 use anyhow::Result;3132 fn get_cluster_info() -> Result<ClusterMap> {33 let config = std::fs::read_to_string("cluster.json")?;34 let map: ClusterMap = serde_json::from_str(&config)?;35 Ok(map)36 }37 ```38Merge pull request #343 from Arthur-Milchior/readme1David Tolnaybefore adoptionf01080b
lines 39–40why, one step back39 [`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html40Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 41–77why, one step back41- Attach context to help the person troubleshooting the error understand where42 things went wrong. A low-level error like "No such file or directory" can be43 annoying to debug without more context about what higher level step the44 application was in the middle of.4546 ```rust47 use anyhow::{Context, Result};4849 fn main() -> Result<()> {50 ...51 it.detach().context("Failed to detach the important thing")?;5253 let content = std::fs::read(path)54 .with_context(|| format!("Failed to read instrs from {}", path))?;55 ...56 }57 ```5859 ```console60 Error: Failed to read instrs from ./path/to/instrs.json6162 Caused by:63 No such file or directory (os error 2)64 ```6566- Downcasting is supported and can be by value, by shared reference, or by67 mutable reference as needed.6869 ```rust70 // If the error was caused by redaction, then return a71 // tombstone instead of the content.72 match root_cause.downcast_ref::<DataStoreError>() {73 Some(DataStoreError::Censored(_)) => Ok(Poll::Ready(REDACTED_CONTENT)),74 None => Err(error),75 }76 ```77Touch up PR 293David Tolnaybefore adoptionb6ac995
lines 78–81why, one step back78- If using Rust ≥ 1.65, a backtrace is captured and printed with the error if79 the underlying error type does not already provide its own. In order to see80 backtraces, they must be enabled through the environment variables described81 in [`std::backtrace`]:Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 82–127why, one step back8283 - If you want panics and errors to both have backtraces, set84 `RUST_BACKTRACE=1`;85 - If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`;86 - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and87 `RUST_LIB_BACKTRACE=0`.8889 [`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variables9091- Anyhow works with any error type that has an impl of `std::error::Error`,92 including ones defined in your crate. We do not bundle a `derive(Error)` macro93 but you can write the impls yourself or use a standalone macro like94 [thiserror].9596 ```rust97 use thiserror::Error;9899 #[derive(Error, Debug)]100 pub enum FormatError {101 #[error("Invalid header (expected {expected:?}, got {found:?})")]102 InvalidHeader {103 expected: String,104 found: String,105 },106 #[error("Missing attribute: {0}")]107 MissingAttribute(String),108 }109 ```110111- One-off error messages can be constructed using the `anyhow!` macro, which112 supports string interpolation and produces an `anyhow::Error`.113114 ```rust115 return Err(anyhow!("Missing attribute: {}", missing));116 ```117118 A `bail!` macro is provided as a shorthand for the same early return.119120 ```rust121 bail!("Missing attribute: {}", missing);122 ```123124<br>125126## No-std support127Reword no-std documentation change from PR 343David Tolnaybefore adoptioncb47d7c
lines 128–130why, one step back128In no_std mode, almost all of the same API is available and works the same way.129To depend on Anyhow in no_std mode, disable our default enabled "std" feature in130Cargo.toml. A global allocator is required.Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 131–136why, one step back131132```toml133[dependencies]134anyhow = { version = "1.0", default-features = false }135```136Merge pull request #385 from dtolnay/docnostdDavid Tolnaybefore adoptionaa3ab2b
lines 137–140why, one step back137With versions of Rust older than 1.81, no_std mode may require an additional138`.map_err(Error::msg)` when working with a non-Anyhow error type inside a139function that returns Anyhow's error type, as the trait that `?`-based error140conversions are defined by is only available in std in those old versions.Update clippy.toml msrv to match rust-version in Cargo.tomlDavid Tolnaybefore adoption553ed38
lines 141–179why, one step back141142<br>143144## Comparison to failure145146The `anyhow::Error` type works something like `failure::Error`, but unlike147failure ours is built around the standard library's `std::error::Error` trait148rather than a separate trait `failure::Fail`. The standard library has adopted149the necessary improvements for this to be possible as part of [RFC 2504].150151[RFC 2504]: https://github.com/rust-lang/rfcs/blob/master/text/2504-fix-error.md152153<br>154155## Comparison to thiserror156157Use Anyhow if you don't care what error type your functions return, you just158want it to be easy. This is common in application code. Use [thiserror] if you159are a library that wants to design your own dedicated error type(s) so that on160failures the caller gets exactly the information that you choose.161162[thiserror]: https://github.com/dtolnay/thiserror163164<br>165166#### License167168<sup>169Licensed under either of <a href="LICENSE-APACHE">Apache License, Version1702.0</a> or <a href="LICENSE-MIT">MIT license</a> at your option.171</sup>172173<br>174175<sub>176Unless you explicitly state otherwise, any contribution intentionally submitted177for inclusion in this crate by you, as defined in the Apache-2.0 license, shall178be dual licensed as above, without any additional terms or conditions.179</sub>