Sub topic 8
Creating errors with anyhow!, bail!, and ensure!
This chapter assumes you know Result and the ? operator, and that you have seen anyhow::Result and Context in the previous chapters. Sometimes a failure has no underlying error to wrap. A value is out of range, or a rule is broken. Three macros in anyhow cover these cases without a custom error type.
Setting up
Add the crate to your project.
cargo add anyhowanyhow!: build an error value
anyhow! creates an anyhow::Error from a format string, in the same way format! creates a String. Use it where you need an error value rather than an early return, for example inside ok_or_else or map_err.
use anyhow::{anyhow, Result};
fn first_word(line: &str) -> Result<&str> {
line.split_whitespace()
.next()
.ok_or_else(|| anyhow!("line {line:?} has no words"))
}
fn main() {
println!("{:?}", first_word("hello world"));
match first_word(" ") {
Ok(word) => println!("word: {word}"),
Err(e) => println!("error: {e}"),
}
}anyhow! also accepts an existing error value. anyhow!(io_error) wraps it, and it keeps the original as the source.
bail!: return early with an error
bail! is shorthand for return Err(anyhow!(...)). It is the usual choice inside an if block.
use anyhow::{bail, Result};
fn parse_level(s: &str) -> Result<u8> {
match s {
"low" => Ok(1),
"high" => Ok(3),
other => bail!("unknown level: {other}"),
}
}
fn main() {
println!("{:?}", parse_level("low"));
println!("{}", parse_level("max").unwrap_err());
}ensure!: check a condition
ensure!(condition, "message") returns an error when the condition is false. It replaces the pattern if !condition { bail!(...) }.
use anyhow::{ensure, Result};
fn set_volume(level: u32) -> Result<u32> {
ensure!(level <= 100, "volume {level} is above 100");
Ok(level)
}
fn main() {
println!("{:?}", set_volume(40));
println!("{}", set_volume(150).unwrap_err());
}If you leave out the message, ensure! generates one from the condition text, such as Condition failed: level <= 100. That is handy in quick scripts, but a written message is more useful to the reader of the error.
The three macros compare as follows.
| Macro | What it does | Typical use |
|---|---|---|
| `anyhow!` | Returns an `anyhow::Error` value | Inside `ok_or_else` and `map_err` |
| `bail!` | Returns `Err` immediately | Branches such as `match` arms and `if` blocks |
| `ensure!` | Returns `Err` if a condition is false | Validating inputs and invariants |
Combining them with context
The macros work with the Context methods from the previous chapter. Use ensure! and bail! for rules you define, and context for failures that come from other libraries.
use anyhow::{bail, ensure, Context, Result};
fn load_port(text: &str) -> Result<u16> {
let port: u16 = text
.trim()
.parse()
.context("port is not a valid u16")?;
ensure!(port >= 1024, "port {port} is reserved");
if port == 8080 {
bail!("port 8080 is already in use");
}
Ok(port)
}
fn main() {
for input in ["3000", "80", "8080", "abc"] {
match load_port(input) {
Ok(p) => println!("ok: {p}"),
Err(e) => println!("error: {e:#}"),
}
}
}The {e:#} format prints the full chain on one line. For abc, you see the context message followed by the parse error.
Common mistakes
- Using these macros in a library's public API. They produce
anyhow::Error, which callers cannot match on. Return athiserrorenum from a library instead. - Messages that lack the bad value.
bail!("invalid port")tells the reader less thanbail!("invalid port: {port}"). - Using
ensure!for programmer bugs. It reports a recoverable error. Useassert!for conditions that should never be false.
Exercise
Rewrite this function using ensure! and bail!. fn check(age: i32) -> anyhow::Result<i32> { if age < 0 { return Err(anyhow::anyhow!("age {age} is negative")); } if age > 150 { return Err(anyhow::anyhow!("age {age} is unrealistic")); } Ok(age) }
Show answer
fn check(age: i32) -> anyhow::Result<i32> { anyhow::ensure!(age >= 0, "age {age} is negative"); if age > 150 { anyhow::bail!("age {age} is unrealistic"); } Ok(age) }. The first check is a single condition, so ensure! fits. The second could use ensure!(age <= 150, ...) as well, and bail! is also correct inside the if.
Exercise
Why should a library's public function avoid returning an error built with bail!?
Show answer
bail! creates an anyhow::Error, which hides the concrete error type. Callers cannot match on variants, so they cannot react to specific failures. A library should return its own enum, defined with thiserror.