Sub topic 3
Handling errors by hand with match, map_err, and friends
This chapter assumes you know Result<T, E> and Option<T>, can read a match expression, and understand closures such as |e| e.to_string(). The ? operator comes in the next chapters. First you need to see the manual code that ? replaces.
Matching on a Result
A Result is an enum with two variants, Ok and Err. A match on it forces you to handle both.
use std::num::ParseIntError;
fn double(s: &str) -> Result<i32, ParseIntError> {
match s.trim().parse::<i32>() {
Ok(n) => Ok(n * 2),
Err(e) => Err(e),
}
}
fn main() {
println!("{:?}", double(" 21 "));
println!("{:?}", double("abc"));
}The Err(e) => Err(e) arm only passes the error along unchanged. Code like this is the typical sign that a combinator would be shorter.
Combinators that change the value or the error
Combinators are methods on Result that take a closure and return a new Result. They replace the common match shapes.
| Method | What it does |
|---|---|
| `map(f)` | Applies `f` to the `Ok` value. An `Err` passes through. |
| `map_err(f)` | Applies `f` to the `Err` value. An `Ok` passes through. |
| `and_then(f)` | Calls `f` on the `Ok` value, where `f` itself returns a `Result`. |
| `unwrap_or(v)` | Returns the `Ok` value, or `v` if it is an `Err`. |
| `unwrap_or_else(f)` | Returns the `Ok` value, or calls `f` with the error. |
| `ok()` | Turns `Result<T, E>` into `Option<T>` and discards the error. |
With map, the earlier function becomes one line:
use std::num::ParseIntError;
fn double(s: &str) -> Result<i32, ParseIntError> {
s.trim().parse::<i32>().map(|n| n * 2)
}Changing the error type with map_err
A function can only return one error type. When it calls operations that fail with different types, you convert each error into a common type. The next example uses String as that type. It first uses match with early returns, then the same logic with map_err and and_then.
use std::fs;
fn read_count_match(path: &str) -> Result<u32, String> {
let text = match fs::read_to_string(path) {
Ok(t) => t,
Err(e) => return Err(format!("cannot read {path}: {e}")),
};
match text.trim().parse::<u32>() {
Ok(n) => Ok(n),
Err(e) => Err(format!("bad number in {path}: {e}")),
}
}
fn read_count_chain(path: &str) -> Result<u32, String> {
fs::read_to_string(path)
.map_err(|e| format!("cannot read {path}: {e}"))
.and_then(|text| {
text.trim()
.parse::<u32>()
.map_err(|e| format!("bad number in {path}: {e}"))
})
}
fn main() {
match read_count_chain("count.txt") {
Ok(n) => println!("count = {n}"),
Err(msg) => eprintln!("error: {msg}"),
}
println!("{:?}", read_count_match("missing.txt"));
}Both functions behave the same. The match version shows the control flow, with each early return marking a failure point. The chained version is shorter but harder to read once the closures nest. Past two or three steps, the chain loses its advantage.
Supplying defaults
Sometimes an error is not worth reporting and a fallback value is enough.
fn main() {
let port: u16 = "80x".parse().unwrap_or(8080);
let retries: u32 = "oops".parse().unwrap_or_else(|_| {
println!("using default retries");
3
});
println!("{port} {retries}");
}Choosing between them
- Use
matchwhen theOkandErrarms do different, substantial work, or when you want to inspect the error and branch on it. - Use
mapandmap_errfor a single transformation. - Use
and_thenwhen the next step can also fail. Usingmapthere would give you a nestedResult<Result<_, _>, _>. - Use
unwrap_orandunwrap_or_elseonly when ignoring the error is correct. Otherwise you hide failures.
These tools work, but every fallible call adds a match arm or a closure layer. The ? operator exists to remove that overhead, and later chapters build on the same ideas. In particular, map_err is what ? does for you when it converts one error type into another.
Exercise
What is the type of "5".parse::<i32>().map(|n| n.to_string().parse::<i32>()), and which combinator would you use instead of map to avoid the nesting?
Show answer
The type is Result<Result<i32, ParseIntError>, ParseIntError>. Using and_then instead of map flattens it to Result<i32, ParseIntError>, because the closure already returns a Result.