In a Rust application using anyhow, what do bail! and ensure! do, and why can one function use ? on both io::Error and ParseIntError?
answer
- early return, not a panic
- Err(anyhow!(...)) in one line
- condition first, message optional
- a blanket From for std errors
basics
~20 sbail!(...) returns early with Err(anyhow!(...)), and ensure!(cond, ...) does the same when cond is false. Both need a Result<_, anyhow::Error> return type. ? accepts both error types because anyhow::Error implements From for every std::error::Error + Send + Sync + 'static.
solid answer
~40 s`bail!("worker count must be positive")` expands to `return Err(anyhow!(...))`. It takes a literal, a format string with arguments, or an error value, and the enclosing function or closure must return `Result<_, anyhow::Error>`, usually written `anyhow::Result<T>`. `ensure!(cond, ...)` is the conditional version: when `cond` is false it returns that error. With no message it builds one from the condition, such as ``Condition failed: `requested <= cores` (16 vs 8)``. Unlike `assert!`, neither one panics. `?` mixes error types because anyhow provides `impl<E> From<E> for anyhow::Error` for every `E: std::error::Error + Send + Sync + 'static`, and both `io::Error` and `ParseIntError` qualify. When `main` returns `anyhow::Result<()>`, an `Err` prints `Error: ...` with its causes and the process exits with a failure status.
code
rust · 28 linesuse anyhow::{bail, ensure, Result};
fn parse_port(raw: &str) -> Result<u16> {
let port: u16 = raw.trim().parse()?; // ParseIntError -> anyhow::Error
ensure!(port >= 1024, "port {port} is privileged");
Ok(port)
}
fn pick_workers(requested: usize, cores: usize) -> Result<usize> {
if requested == 0 {
bail!("worker count must be positive");
}
ensure!(requested <= cores);
Ok(requested)
}
fn main() -> Result<()> {
for raw in ["8080", "80", "http"] {
match parse_port(raw) {
Ok(p) => println!("{raw}: ok {p}"),
Err(e) => println!("{raw}: {e}"),
}
}
println!("{}", pick_workers(0, 8).unwrap_err());
println!("{}", pick_workers(16, 8).unwrap_err());
let _cfg = std::fs::read_to_string("/nonexistent/app.toml")?; // io::Error
Ok(())
}go deeper
Recall that bail! means return an error now, ensure! means return an error if this check fails, and neither one panics.
Explain the blanket From impl that lets ? absorb any std error, and why bail! requires an anyhow::Error return type.
Show judgement about where these belong: in binaries and glue, ensure! for input-driven checks, and typed errors wherever a caller has to branch.
Set the rule for the codebase: anyhow macros at the application edge only, and never in a library crate's public functions.
## `anyhow::Result` and `?` In application code (a command-line tool, a service's startup path, a batch job) the usual goal is that any failure stops the current operation and gets reported clearly. anyhow is built for that: - `anyhow::Result<T>` is a type alias for `Result<T, anyhow::Error>`. - `anyhow::Error` can hold any error type that implements `std::error::Error + Send + Sync + 'static`. - anyhow provides a **blanket conversion**, `impl<E> From<E> for anyhow::Error` with exactly those bounds. The `?` operator returns early on `Err` and passes the error through `From::from` on the way out. (The general rules of `?` belong with the material on the question-mark operator.) Because of anyhow's blanket `From`, a single function can use `?` on `std::fs::read_to_string` (an `io::Error`), on `str::parse::<u16>` (a `ParseIntError`) and on a library call returning a thiserror enum, with no `map_err` anywhere. ## `bail!`: return an error right here `bail!` is shorthand for an early return. Its documentation says it "is equivalent to `return Err(anyhow!($args...))`". It accepts three forms: 1. A string literal, `bail!("worker count must be positive")`. 2. A format string with arguments, `bail!("port {} is privileged", port)`. Inline arguments such as `{port}` work as well. 3. An error value, `bail!(StorageError::NotFound { id })`. The value keeps its concrete type inside the `anyhow::Error`, so `downcast_ref` can find it later. The enclosing function, or closure, must return `Result<_, anyhow::Error>`. In a function returning `Result<u32, StorageError>`, `bail!` fails with `E0308` (mismatched types, "expected `StorageError`, found `Error`"), because a plain `return Err(...)` applies no `From` conversion. ## The `anyhow!` macro underneath Both macros build their error with `anyhow!`, which you can also call directly as `return Err(anyhow!(...))` or pass to `map_err`. It evaluates to an `anyhow::Error` and accepts: - a string literal or a format string with arguments, which becomes a message-only error; - any value implementing `Debug` and `Display`, even one that does not implement `std::error::Error`; - a value whose type implements `std::error::Error`, in which case, as the docs put it, "that Error impl's `source` is preserved as the `source` of the resulting `anyhow::Error`". So `bail!(err)` with a real error value keeps both its type and its cause chain, while `bail!("{err}")` keeps only the text. That difference matters later if some code needs to downcast or print the causes. ## `ensure!`: a check that returns instead of panicking `ensure!(cond, ...)` is equivalent to `if !cond { return Err(anyhow!(...)); }`. - With a message, `ensure!(port >= 1024, "port {port} is privileged")` returns that message when the check fails. - Without a message, anyhow builds one from the condition's source text. For a comparison it also shows both operands, so `ensure!(requested <= cores)` with 16 and 8 produces ``Condition failed: `requested <= cores` (16 vs 8)``. - anyhow's docs compare it with `assert!`: it "takes a condition and exits the function if the condition fails", but it returns an `Error` "rather than panicking". The `assert!` family and when panicking is acceptable belong with the material on panics. ## Returning from `main` `fn main() -> anyhow::Result<()>` works because std implements its `Termination` trait for `Result<T, E>` when `T` implements it (as `()` does) and `E: Debug`. On `Err`, std prints `Error: {err:?}` to standard error and returns `ExitCode::FAILURE`. anyhow's `Debug` output is the message, then a `Caused by:` list of the source chain, plus a backtrace if one was captured and backtraces are enabled. A missing config file therefore ends the program with `Error: No such file or directory (os error 2)` and a non-zero exit status. ## What these macros are not | Misreading | What actually happens | |---|---| | `bail!` is a panic | it returns `Err` from the enclosing function | | `ensure!` only runs in debug builds | it is always evaluated; `debug_assert!` is the debug-only one | | works with any `Result` | needs `Result<_, anyhow::Error>` | | `?` needs `map_err` first | anyhow's blanket `From` does the conversion | ## When to use them - In binaries and top-level glue, where the caller of a failure is a person reading a message. - Not in a library's public functions. There a caller usually needs typed variants to match on, which a thiserror enum provides.
- What happens if you write `bail!` inside a function returning `Result<u32, StorageError>`?It does not compile. `bail!` expands to `return Err(anyhow!(...))`, so it produces an `anyhow::Error`, and a plain `return` applies no `From` conversion. rustc reports E0308 mismatched types: "expected `StorageError`, found `Error`". anyhow's docs state that the surrounding function or closure must return `Result<_, anyhow::Error>`.
- When would you pick `ensure!` over `assert!` in an application?When the condition depends on input or on the environment, such as a port number from a config file or a worker count from a flag. `ensure!` returns an `Err` the caller can report or recover from. `assert!` panics, which suits an invariant whose failure would mean a bug in the code itself.
- bail! panics with its message, just like panic!.
- ensure! is only checked in debug builds, like debug_assert!.
- ? needs map_err before an io::Error can become an anyhow::Error.
- bail! works in any function returning a Result, whatever its error type.