Sub topic 3
Handling errors by hand with match, map_err, and friends
Before ? makes error handling short, you need to know what it replaces. This chapter covers the manual tools: match, if let, let ... else, and the methods on Result. They are still useful after you learn ?, because ? only covers the case where you want to return the error unchanged or convert it. Everything else, such as recovering, supplying a default, or adding context, uses the tools below.
Prerequisites
This chapter assumes you can read and write basic Rust: functions, enums, and match. It also assumes you know that Result<T, E> has the variants Ok(T) and Err(E), and that you can run code with Cargo. Closures such as |e| e.to_string() appear throughout. A closure is an inline anonymous function.
Matching on a Result
Result is an ordinary enum, so match is the most direct way to handle it. The compiler requires you to cover both variants, so you cannot forget the error case.
use std::fs;
fn read_count(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!("cannot parse {path}: {e}")),
}
}
fn main() {
match read_count("count.txt") {
Ok(n) => println!("count = {n}"),
Err(msg) => eprintln!("error: {msg}"),
}
}The function has two failure points, and each needs its own match. The first match either yields the file text or returns early. The second match produces the final value. With three or four fallible steps, this style turns into a ladder of repeated Ok(v) => v, Err(e) => return Err(...) arms. That repetition is what ? removes in the next chapter.
Note that both errors were converted into a String. The function's return type has one error type, but fs::read_to_string fails with io::Error and parse fails with ParseIntError. Each Err arm therefore converts the error into the type the function promises.
if let and let ... else
Sometimes you care about only one variant. if let handles that without a full match.
fn main() {
if let Err(e) = "12x".parse::<i32>() {
println!("parse failed: {e}");
}
}let ... else is the better fit when the success value is needed for the rest of the function. The else block must leave the current scope, by returning, breaking, continuing, or panicking.
fn describe(input: &str) -> String {
let Ok(n) = input.parse::<i32>() else {
return format!("{input:?} is not a number");
};
format!("{n} doubled is {}", n * 2)
}
fn main() {
println!("{}", describe("21"));
println!("{}", describe("abc"));
}This keeps the success path unindented, much like ? does. The cost is that the else branch cannot see the error value, so you lose the reason for the failure. If you need it, use match or map_err.
Transforming values with map and map_err
Two methods change one side of a Result and leave the other alone.
mapapplies a function to theOkvalue. AnErrpasses through untouched.map_errapplies a function to theErrvalue. AnOkpasses through untouched.
map_err is the one you will use most. It converts or enriches an error without a match.
fn parse_port(text: &str) -> Result<u16, String> {
text.trim()
.parse::<u16>()
.map_err(|e| format!("bad port {text:?}: {e}"))
}
fn main() {
println!("{:?}", parse_port("8080"));
println!("{:?}", parse_port("99999"));
}The first call prints Ok(8080). The second prints an Err containing the message, because 99999 does not fit in a u16.
Chaining with and_then
map takes a function that returns a plain value. When the next step can also fail, the function returns a Result, and map would give you a nested Result<Result<_, _>, _>. and_then handles this case: it runs the function on the Ok value and returns whatever Result the function produces.
Here is read_count again, with no match and no early return:
use std::fs;
fn read_count(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!("cannot parse {path}: {e}"))
})
}
fn main() {
println!("{:?}", read_count("count.txt"));
}The first map_err aligns the error type to String. Then and_then runs only if the read succeeded. This works, but each additional step adds another nesting level, and and_then closures cannot use return to leave the outer function. For long sequences, ? reads better.
Recovering and supplying defaults
Other methods turn a Result into a plain value or replace a failure with something else.
| Method | Effect |
|---|---|
| `unwrap_or(v)` | Returns the `Ok` value, or `v` on `Err`. `v` is always computed first. |
| `unwrap_or_else(f)` | Returns the `Ok` value, or calls `f(error)` on `Err`. |
| `unwrap_or_default()` | Returns the `Ok` value, or `T::default()` on `Err`. |
| `or_else(f)` | On `Err`, calls `f(error)`, which returns another `Result`. |
| `ok()` | Converts to `Option<T>`, dropping the error. |
| `is_ok()` / `is_err()` | Returns a `bool` without consuming the value. |
The following program checks each of them:
use std::num::ParseIntError;
fn main() {
let good: Result<i32, ParseIntError> = "21".parse();
let bad: Result<i32, ParseIntError> = "abc".parse();
assert_eq!(good.clone().map(|n| n * 2), Ok(42));
assert_eq!(bad.clone().unwrap_or(0), 0);
assert_eq!(bad.clone().unwrap_or_else(|_| -1), -1);
assert_eq!(bad.clone().unwrap_or_default(), 0);
assert_eq!(bad.clone().or_else(|_| "7".parse::<i32>()), Ok(7));
assert_eq!(good.clone().ok(), Some(21));
assert_eq!(bad.clone().ok(), None);
assert!(bad.is_err());
let checked = "500"
.parse::<i32>()
.map_err(|e| e.to_string())
.and_then(|n| {
if n > 100 {
Err(format!("{n} is too large"))
} else {
Ok(n)
}
});
assert_eq!(checked, Err("500 is too large".to_string()));
println!("all checks passed");
}Eager versus lazy arguments
unwrap_or(expensive()) calls expensive() every time, even when the result is Ok and the default is never used. unwrap_or_else(|_| expensive()) calls it only on Err. Use the _else form whenever the fallback costs something, such as an allocation, a file read, or a function call with side effects.
Choosing between the tools
Pick the tool by what you want to do with the error.
- Handle each case differently, or log and continue: use
match. - Care about one case only: use
if letorlet ... else. - Change the error type or add context: use
map_err. - Transform a success value: use
map. - Run a further step that can fail: use
and_then. - Fall back to a default or another source: use
unwrap_or_elseoror_else. - Pass the error up to the caller unchanged: use
?, covered next.
Common mistakes
- Using
mapwhen the closure returns aResult. You get a nestedResult. Switch toand_then. - Mismatched error types in a chain.
and_thenrequires the closure's error type to equal the existing one. Callmap_errfirst to align them, asread_countdoes above. - Converting every error to
Stringtoo early. AStringkeeps the message but loses the original error type, so callers cannot match on it or inspect its source. Chapter on custom error types shows a better design. - Using
unwrap_or(expensive()). The argument is evaluated eagerly. Useunwrap_or_else. - Forgetting that
let ... elsemust diverge. If theelseblock can fall through, the compiler rejects it.
Exercise
Write fn double_port(text: &str) -> Result<u16, String> that parses text as a u16, then doubles it, using only map_err and and_then, with no match and no ?. If parsing fails, the error should be the string "not a port". If doubling would overflow a u16, the error should be "too big". Which u16 method helps with the overflow check?
Show answer
Use text.trim().parse::<u16>().map_err(|_| "not a port".to_string()).and_then(|p| p.checked_mul(2).ok_or_else(|| "too big".to_string())). The checked_mul method returns Option<u16>, which is None on overflow, and ok_or_else turns that None into the Err("too big") value. The first map_err makes the error type String so that and_then can return a String error. For example, double_port("40000") returns Err("too big"), and double_port("21") returns Ok(42).
Exercise
A function calls config.get("timeout").unwrap_or(load_default_from_disk()), where load_default_from_disk reads a file. What is wrong, and how do you fix it?
Show answer
unwrap_or evaluates its argument eagerly, so the file is read on every call, even when "timeout" is present. Replace it with unwrap_or_else(|| load_default_from_disk()), or pass the function directly as unwrap_or_else(load_default_from_disk), so the read happens only when the value is missing.