anyhow
Flexible Anwendungsfehler
anyhow ist eine kostenlose Learn Rust Coding-Lektion auf CoddyKit. Dies ist Lektion 3 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Learn Rust Coding-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
Flexible Application Errors
In application code you often just want errors to bubble up with context, without defining a typed enum for each. The anyhow crate provides one easy error type for exactly that.
Adding anyhow
Add it as a dependency. It pairs well with thiserror: thiserror for libraries, anyhow for binaries.
[dependencies]
anyhow = "1.0"The anyhow::Result Alias
anyhow::Result<T> is shorthand for Result<T, anyhow::Error>. The Error type can hold any error that implements std::error::Error.
use anyhow::Result;
fn load() -> Result<String> {
let text = std::fs::read_to_string("config.txt")?;
Ok(text)
}Automatic Conversion
The ? operator converts any standard error into anyhow::Error automatically, so you can mix error types freely.
use anyhow::Result;
fn parse_file(path: &str) -> Result<i32> {
let text = std::fs::read_to_string(path)?; // io error
let n: i32 = text.trim().parse()?; // parse error
Ok(n)
}Adding Context
The .context() method attaches a human-friendly message to an error, building a readable chain when things fail.
use anyhow::{Context, Result};
fn read_config(path: &str) -> Result<String> {
let text = std::fs::read_to_string(path)
.context("failed to read config file")?;
Ok(text)
}Lazy Context
Use with_context when building the message is expensive or needs runtime data; the closure runs only on error.
use anyhow::{Context, Result};
fn open(path: &str) -> Result<String> {
std::fs::read_to_string(path)
.with_context(|| format!("could not open {path}"))
}Creating Ad-hoc Errors
The anyhow! macro builds an error from a message, and bail! returns early with one.
use anyhow::{anyhow, bail, Result};
fn check(age: i32) -> Result<()> {
if age < 0 {
bail!("age cannot be negative");
}
if age > 150 {
return Err(anyhow!("age {age} is implausible"));
}
Ok(())
}Using ensure!
ensure! is like assert! but returns an error instead of panicking.
use anyhow::{ensure, Result};
fn divide(a: i32, b: i32) -> Result<i32> {
ensure!(b != 0, "division by zero");
Ok(a / b)
}anyhow in main
Return anyhow::Result<()> from main to get nicely formatted error chains printed on failure.
use anyhow::Result;
fn main() -> Result<()> {
let text = std::fs::read_to_string("data.txt")?;
println!("{text}");
Ok(())
}Inspecting the Cause
Even though anyhow::Error is opaque, you can still inspect it. downcast_ref recovers a concrete error type when you need to branch on it.
use anyhow::Result;
fn report(err: anyhow::Error) {
if let Some(io) = err.downcast_ref::<std::io::Error>() {
println!("io error: {io}");
} else {
println!("other error: {err}");
}
}thiserror vs anyhow
Rule of thumb:
- thiserror — libraries, typed errors callers match on
- anyhow — applications, just propagate with context
You can convert a thiserror error into anyhow with ? seamlessly.
Quick Check
Which anyhow method attaches a descriptive message to an error as it propagates?
Recap
You learned the anyhow crate:
anyhow::Result<T>uses one flexible error type?converts any standard error automatically.context()/with_context()add readable messagesanyhow!,bail!, andensure!create errors- Best for application (binary) code
Häufig gestellte Fragen
Ist die Lektion „anyhow“ kostenlos?
Ja — der vollständige Text von „anyhow“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Learn Rust Coding-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Learn Rust Coding-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „anyhow“?
Flexible Anwendungsfehler Du übst Learn Rust Coding mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Learn Rust Coding zu starten?
Keine Vorkenntnisse erforderlich. Learn Rust Coding auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 3 von 4.
Wie lange dauert die Lektion „anyhow“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Learn Rust Coding-Lektion Code schreiben und ausführen?
Ja. Jede Learn Rust Coding-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.