anyhow
- Rust course
- Intermediate
- Lesson 67/115
- 4 min
Do flexible error handling with the anyhow crate.
anyhow
In applications, gathering errors from different sources into a single type is often enough. anyhow::Result<T> is shorthand for Result<T, anyhow::Error> and accepts any error type via ?:
// Cargo.toml: anyhow = "1"
use anyhow::{bail, Result};
fn oku(s: &str) -> Result<i32> {
let n: i32 = s.trim().parse()?;
if n == 0 {
bail!("sıfır olamaz");
}
Ok(100 / n)
}bail! returns Err immediately with a formatted message. Its closest standard library counterpart is Box<dyn Error>.
The same pattern with std
In the exercise we'll use the standard counterpart instead of anyhow; the structure is the same:
use std::error::Error;
fn oku(s: &str) -> Result<i32, Box<dyn Error>> {
let n: i32 = s.trim().parse()?; // ParseIntError → Box
if n == 0 {
return Err("sıfır olamaz".into()); // &str → Box
}
Ok(100 / n)
}On top of this, anyhow offers adding context, printing the error chain and backtraces.
Practice Flexible error type
Write the oku function above with Box<dyn Error>. For "4", "abc" and "0", print the result on success and hata: MESSAGE on error.
Starter code
use std::error::Error;
fn main() {
// buraya yaz
}Sample solution
use std::error::Error;
fn oku(s: &str) -> Result<i32, Box<dyn Error>> {
let n: i32 = s.trim().parse()?;
if n == 0 {
return Err("sıfır olamaz".into());
}
Ok(100 / n)
}
fn main() {
for g in ["4", "abc", "0"] {
match oku(g) {
Ok(n) => println!("{}", n),
Err(e) => println!("hata: {}", e),
}
}
}Expected output
25 hata: invalid digit found in string hata: sıfır olamaz
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 How is a string converted into a <code>Box<dyn Error></code>?
- panic!("mesaj")
- "mesaj".into() or Box::from("mesaj") Correct answer
- It can't be
- Error::new("mesaj")
Explanation: The standard library provides From<..> for Box<dyn Error> for &str and String.
2 Error from text
if n == 0 {
return Err("sıfır olamaz".____());
}
if n == 0 {
return Err("sıfır olamaz".into());
}
Explanation: into converts the &str into a Box<dyn Error>.
3 Input and oku result
| Term | Meaning |
|---|---|
"4" |
25 |
" 10 " |
10 |
"abc" |
invalid digit found in string |
"0" |
sıfır olamaz |