Sub topic 8
Creating errors with anyhow!, bail!, and ensure!
This chapter assumes you can write functions that return anyhow::Result, use ? to propagate errors, and attach messages with Context. It covers the three macros that create new anyhow errors when no underlying error exists yet.
When no error exists yet
? and .context(...) handle failures that come from somewhere else, such as a failed read_to_string or parse. Some failures start in your own code:
- A parsed value is out of range.
- A required key is absent.
- A line has the wrong shape.
- A state you consider impossible has been reached.
No library call returned an Err for these cases, so you create the error yourself. anyhow provides three macros for this.
| Macro | What it does | Closest hand-written form |
|---|---|---|
| `anyhow!(...)` | Builds an `anyhow::Error` value | `anyhow::Error::msg(format!(...))` |
| `bail!(...)` | Builds an error and returns it | `return Err(anyhow!(...));` |
| `ensure!(cond, ...)` | Returns an error if `cond` is false | `if !cond { bail!(...); }` |
All three accept the same message forms:
- A string literal:
"plain text". - A format string with arguments:
"port {}", port. - Inline captures:
"port {port}". - A single expression that is already an error value.
anyhow!: build an error value
Use anyhow! when you need the error as a value instead of returning it immediately. The usual case is a closure passed to ok_or_else, map_err, or unwrap_or_else.
use anyhow::{anyhow, Result};
fn first_word(text: &str) -> Result<&str> {
text.split_whitespace()
.next()
.ok_or_else(|| anyhow!("input `{text}` contains no words"))
}
fn main() {
println!("{:?}", first_word("hello world").unwrap());
println!("{}", first_word(" ").unwrap_err());
}This prints "hello" and then `input contains no words`.
anyhow! also accepts a value that already implements std::error::Error. In that case the value is wrapped as is, not flattened to text, so its type survives and you can recover it later:
use anyhow::{anyhow, Result};
use std::io;
fn open_cache() -> Result<()> {
Err(anyhow!(io::Error::new(
io::ErrorKind::NotFound,
"cache directory missing"
)))
}
fn main() {
let err = open_cache().unwrap_err();
let kind = err.downcast_ref::<io::Error>().map(|e| e.kind());
println!("{kind:?}");
}This prints Some(NotFound). If you had written anyhow!("cache directory missing"), the downcast_ref::<io::Error>() call would return None. A string message becomes an opaque error that carries only text.
bail!: return early with an error
bail! is return Err(anyhow!(...)) in one line. It fits guard clauses, match arms, and let ... else blocks, where the failing branch must leave the function.
use anyhow::{anyhow, bail, ensure, Result};
#[derive(Debug)]
struct Settings {
name: String,
workers: usize,
port: u16,
}
fn parse_line(line_no: usize, line: &str) -> Result<(&str, &str)> {
let Some((key, value)) = line.split_once('=') else {
bail!("line {line_no}: expected `key=value`, got `{line}`");
};
Ok((key.trim(), value.trim()))
}
fn parse_settings(text: &str) -> Result<Settings> {
let mut name = None;
let mut workers = 4usize;
let mut port = None;
for (idx, line) in text.lines().enumerate() {
if line.trim().is_empty() {
continue;
}
let (key, value) = parse_line(idx + 1, line)?;
match key {
"name" => name = Some(value.to_string()),
"workers" => workers = value.parse()?,
"port" => port = Some(value.parse::<u16>()?),
other => bail!("line {}: unknown key `{other}`", idx + 1),
}
}
let name = name.ok_or_else(|| anyhow!("missing required key `name`"))?;
let port = port.ok_or_else(|| anyhow!("missing required key `port`"))?;
ensure!(workers >= 1, "workers must be at least 1, got {workers}");
ensure!(port >= 1024, "port {port} is reserved");
Ok(Settings { name, workers, port })
}
fn main() {
let inputs = [
"name=api\nport=8080\nworkers=8",
"name=api\nport=80",
"name=api\nport=9000\nworkers=0",
"port=9000",
"name=api\nport=abc",
"name api",
"name=api\ncolour=blue\nport=9000",
];
for text in inputs {
match parse_settings(text) {
Ok(s) => println!("ok: {s:?}"),
Err(e) => println!("error: {e}"),
}
}
}The program prints:
ok: Settings { name: "api", workers: 8, port: 8080 }
error: port 80 is reserved
error: workers must be at least 1, got 0
error: missing required key `name`
error: invalid digit found in string
error: line 1: expected `key=value`, got `name api`
error: line 2: unknown key `colour`Three things in this example are worth noting:
bail!has type!(never), so it works as amatcharm whose siblings evaluate to().value.parse()?produces aParseIntError, and?converts it intoanyhow::Errorautomatically. Errors that already exist go through?. Errors you invent go through the macros.- The message for a bad port,
invalid digit found in string, does not say which key failed. Adding.with_context(...)there would fix that.
ensure!: a check that returns an error
ensure!(condition, message...) expands to a check followed by bail!. It is the error-returning counterpart of assert!:
assert!panics and is meant for bugs in your own code.ensure!returns anErrand is meant for bad input or bad external state.
If you leave out the message, anyhow builds one from the condition's source text:
use anyhow::{ensure, Result};
fn check_workers(workers: usize) -> Result<()> {
ensure!(workers >= 1);
Ok(())
}
fn main() {
println!("{}", check_workers(0).unwrap_err());
}The message looks like `Condition failed: workers >= 1 . For comparisons between values that implement Debug, recent anyhow` versions also append the operand values. The exact text is not a stable contract, so do not match on it in tests or code. Write an explicit message for anything a user or a log reader will see.
Choosing between the macros
Pick the macro by how the failure appears in your code.
In practice:
- Use
ensure!for preconditions at the top of a function. - Use
bail!insideif,match, andelsebranches. - Use
anyhow!insideok_or_else,map_err, andunwrap_or_elseclosures.
Gotchas and edge cases
The return type must be anyhow::Error
bail! and ensure! expand to return Err(<anyhow::Error>). A bare return Err(x) does not apply From conversion, so the function's error type must be exactly anyhow::Error. Calling either macro in a function that returns Result<u16, ConfigError> fails with a mismatched-types error. In a thiserror-based function, add a variant for the failure and return it:
use thiserror::Error;
#[derive(Debug, Error)]
pub enum PortError {
#[error("port {0} is reserved")]
Reserved(u16),
}
pub fn check_port(port: u16) -> Result<u16, PortError> {
if port < 1024 {
return Err(PortError::Reserved(port));
}
Ok(port)
}Typed errors can still go through the macros
If application code calls a function that returns a typed error and you want to fail with a typed error from the application layer, pass the value to bail!. The call bail!(PortError::Reserved(80)) stores the PortError, so err.downcast_ref::<PortError>() finds it later. Pass an error value to the macros when callers need to react to the failure. Use a message string when the text is all anyone needs.
Do not flatten errors you already have
This pattern looks reasonable but discards information:
use anyhow::{anyhow, Result};
fn read_port(path: &str) -> Result<String> {
std::fs::read_to_string(path)
.map_err(|e| anyhow!("could not read {path}: {e}"))
}The io::Error is converted to text. The error chain is gone and downcast_ref::<io::Error>() returns None. Use .with_context(|| format!("could not read {path}")) instead, which keeps the original error as the source.
A lone expression is a message, not a format string
bail!(user_text) with a String variable treats the value as the message. The text is not parsed for {} placeholders, so braces in user input are safe. When you want formatting, write the literal explicitly: bail!("bad input: {user_text}").
Messages are for people
Write messages as short lowercase fragments without a trailing period, such as port 80 is reserved. Report printers join the chain with : or list the causes line by line, and sentences with capital letters and periods read badly in that format. Include the offending value and, where it helps, the constraint it violated.
Summary of the model
anyhow!creates ananyhow::Errorfrom text or from an existing error value.bail!returns that error immediately.ensure!checks a condition first and then bails.- Wrapping an existing error value keeps its type available for downcasting. Formatting it into text loses the type and the chain.
- All three require the function to return
Result<_, anyhow::Error>.
Exercise
A function returns anyhow::Result<()> and contains ensure!(retries <= 5, "retries {retries} exceeds the limit of 5");. Rewrite this check as an if statement that uses bail!. Then say what happens if the same function instead returns Result<(), MyError> where MyError is a thiserror enum.
Show answer
if retries > 5 { bail!("retries {retries} exceeds the limit of 5"); }. If the return type is Result<(), MyError>, the code does not compile. ensure! and bail! expand to return Err(anyhow::Error), which does not match MyError, and return Err(x) applies no From conversion. Add a variant to MyError and return it directly.
Exercise
You write std::fs::read_to_string(path).map_err(|e| anyhow!("read failed: {e}"))?. A caller later tries err.downcast_ref::<std::io::Error>() on the result and gets None. Why, and what are two ways to fix it?
Show answer
The closure formats the io::Error into a string, so anyhow! receives only text. The original error is neither stored nor available as a source. Fix it either by passing the error value, as in map_err(|e| anyhow!(e)) (or simply using ?), or by using .with_context(|| format!("read failed for {path}")). Both keep the io::Error inside the anyhow::Error, so downcast_ref::<std::io::Error>() succeeds.