Sub topic 2
Application Errors with `anyhow::Result`
Assume you know Rust functions, Result, the ? operator, traits, and Cargo dependencies. This chapter uses the anyhow crate, which is useful for application code when you want to propagate failures and add context without defining an error enum for every operation.
Application errors with `anyhow::Result`
anyhow::Error is a general-purpose error type. anyhow::Result<T> is an alias for Result<T, anyhow::Error>.
The ? operator returns early when an operation fails. anyhow can store many different error types, so errors from file reading, parsing, and validation can travel through the same function.
use anyhow::{Context, Result};
use std::fs;
fn load_port(path: &str) -> Result<u16> {
let text = fs::read_to_string(path)
.with_context(|| format!("failed to read {path}"))?;
let port = text
.trim()
.parse::<u16>()
.context("port is not a valid u16")?;
Ok(port)
}
fn main() -> Result<()> {
let port = load_port("port.txt")?;
println!("listening on {port}");
Ok(())
}Returning Result<()> from main lets Rust print an unhandled error and exit unsuccessfully.
Explaining what failed with context
context adds a fixed message to an error. with_context accepts a closure, so it can build a message using values such as a file path. The original error remains available as the source.
flowchart TD
A[read_to_string fails] --> B[Add file path context]
B --> C[? returns anyhow::Error]
C --> D[main reports the chain]Creating errors with macros
Use anyhow! to create an error value, bail! to return an error immediately, and ensure! to reject a false condition.
use anyhow::{bail, ensure, Result};
fn validate_port(port: u16) -> Result<()> {
ensure!(port >= 1024, "port {port} is reserved");
if port == 8080 {
bail!("port {port} is already in use");
}
Ok(())
}
fn check_name(name: &str) -> Result<()> {
if name.is_empty() {
return Err(anyhow::anyhow!("name cannot be empty"));
}
Ok(())
}Use these macros for application rules that do not need public, matchable error variants. A reusable library usually exposes a structured error type instead.
Exercise
Which macro should you use to return an error when a condition is false?
Show answer
Use ensure!(condition, "message"). It returns an error when the condition is false.