Sub topic 17
Designing fallible APIs: when to return, when to panic
This chapter assumes you know Option, Result, the ? operator, custom error enums, and how unwrap and expect panic. It gives you a way to decide which tool fits each failure in your own functions.
Bugs panic, expected failures return
A panic means the program has a bug. A returned error means the world did not cooperate. Bad user input, a missing file, and a dropped network connection are all normal events, so they belong in a return type. A broken internal invariant, such as an index your own code should have kept in range, is a bug, and a panic is acceptable.
Option or Result
Use Option when there is one obvious reason for failure, such as "not found" or "empty". Use Result when the caller could react differently to different causes, or when a message would help a human. Avoid Result<T, String> in public APIs. Callers cannot match on a string, and you cannot change the wording later without breaking them.
A small example
use std::fmt;
#[derive(Debug, PartialEq)]
enum PortError {
NotANumber,
Zero,
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortError::NotANumber => write!(f, "port is not a number"),
PortError::Zero => write!(f, "port must not be zero"),
}
}
}
impl std::error::Error for PortError {}
/// Parses a TCP port.
///
/// # Errors
/// Returns `PortError::NotANumber` if `s` is not a `u16`,
/// and `PortError::Zero` if it parses to 0.
fn parse_port(s: &str) -> Result<u16, PortError> {
let n: u16 = s.trim().parse().map_err(|_| PortError::NotANumber)?;
if n == 0 {
Err(PortError::Zero)
} else {
Ok(n)
}
}
fn main() {
// Input we wrote ourselves: failure here would be a bug, so expect is fine.
let default = parse_port("8080").expect("default port literal is valid");
println!("default = {default}");
// Input from outside: handle the error.
for raw in ["9000", "0", "web"] {
match parse_port(raw) {
Ok(p) => println!("{raw}: ok {p}"),
Err(e) => println!("{raw}: {e}"),
}
}
}The function returns an error for outside input. main uses expect only on a literal it controls, and the message states why the call cannot fail.
Guidelines for your API
- Write an
# Errorssection in the doc comment for every function that returnsResult, and a# Panicssection for any function that can panic. - Make panicking a deliberate choice. If a function panics on bad input, consider offering a checked version too. The standard library does this:
v[i]panics, whilev.get(i)returns anOption. - Never panic on data you do not control, such as files, network input, or user arguments.
- In libraries, return a specific error type so callers can match on it. In applications,
Box<dyn Error>is usually enough. - Use
unwrapfreely in tests and short examples. In production code, preferexpectwith a message that states the invariant.
Common mistakes
- Returning
Optionand discarding the reason, which leaves the caller unable to report a useful message. - Calling
unwrapon parsed input "just for now" and shipping it. - Exposing a third-party error type directly in your public API. A dependency upgrade then becomes a breaking change for your callers. Wrap it in your own variant instead.
Exercise
A function reads a line of user input and must turn it into a positive count. It can fail because the text is not a number, or because the number is zero. Should it return Option, Result, or panic, and why?
Show answer
It should return Result. User input is an expected source of failure, so panicking is wrong. The two causes need different messages, so Option would lose information. A small error enum with variants for "not a number" and "zero" lets the caller match on the cause.