thiserror 和 anyhow
The thiserror and anyhow crates are widely used to simplify error handling.
thiserroris often used in libraries to create custom error types that implementFrom<T>.anyhowis often used by applications to help with error handling in functions, including adding contextual information to your errors.
1. use anyhow::{bail, Context, Result};
2. use std::fs;
3. use std::io::Read;
4. use thiserror::Error;
6. #[derive(Clone, Debug, Eq, Error, PartialEq)]
7. #[error("Found no username in {0}")]
8. struct EmptyUsernameError(String);
10. fn read_username(path: &str) -> Result<String> {
11. let mut username = String::with_capacity(100);
12. fs::File::open(path)
13. .with_context(|| format!("Failed to open {path}"))?
14. .read_to_string(&mut username)
15. .context("Failed to read")?;
16. if username.is_empty() {
17. bail!(EmptyUsernameError(path.to_string()));
18. }
19. Ok(username)
20. }
22. fn main() {
23. //fs::write("config.dat", "").unwrap();
24. match read_username("config.dat") {
25. Ok(username) => println!("Username: {username}"),
26. Err(err) => println!("Error: {err:?}"),
27. }
28. }
This slide should take about 5 minutes.
thiserror
- The
Errorderive macro is provided bythiserror, and has lots of useful attributes to help define error types in a compact way. - The
std::error::Errortrait is derived automatically. - The message from
#[error]is used to derive theDisplaytrait.
anyhow
anyhow::Erroris essentially a wrapper aroundBox<dyn Error>. As such it’s again generally not a good choice for the public API of a library, but is widely used in applications.anyhow::Result<V>is a type alias forResult<V, anyhow::Error>.- Actual error type inside of it can be extracted for examination if necessary.
- Functionality provided by
anyhow::Result<T>may be familiar to Go developers, as it provides similar usage patterns and ergonomics to(T, error)from Go. anyhow::Contextis a trait implemented for the standardResultandOptiontypes.use anyhow::Contextis necessary to enable.context()and.with_context()on those types.
