Sub topic 17
Designing Fallible APIs: When to Return, When to Panic
This chapter assumes you know Option, Result, the ? operator, From conversions, and how unwrap and expect behave. It turns those tools into design rules for your own functions. The rules decide what a function returns, what it panics on, and which error type it exposes.
Whose mistake is it?
When a function can't do its job, ask who is responsible.
- The outside world is responsible. Examples are a missing file, a malformed number, a closed socket, or a user typing
abcfor a port. These conditions are expected in a correct program. Return a value:OptionorResult. - The caller broke the function's contract. Examples are an index out of bounds, an empty slice passed to a function that documents "must not be empty", or a state the program has already ruled out. This is a bug. Panic, and say so in the documentation.
Option or Result?
Use Option<T> when there is exactly one way to have nothing and the meaning is clear from the function name. slice.first() returns None only because the slice is empty. Use Result<T, E> when the caller could do something different depending on why it failed, or when the reason belongs in a log.
| Situation | Return type | Reason |
|---|---|---|
| Look up a key in a map | `Option<&V>` | Absence is the only outcome besides success |
| Parse text into a number | `Result<T, ParseIntError>` | The caller needs to know what was wrong with the text |
| Read a file | `Result<String, io::Error>` | Many distinct failures: missing, denied, not UTF-8 |
| Find the first match in a list | `Option<T>` | "No match" is a normal answer |
A common mistake is returning Option and throwing away the reason. If you later need the reason, changing Option<T> to Result<T, E> breaks every caller. Choose Result early when you suspect the reason will matter.
When a panic is the right answer
Panics are for bugs, not for conditions you expect. These cases are legitimate:
- Contract violations. The function documents a precondition and the caller broke it. The standard library does this with slice indexing,
RefCell::borrow_mut, and integer division by zero. - Broken internal invariants. If your own data structure is in a state that your code should make impossible, continuing would only spread corrupt data.
- Tests, examples, and prototypes. A failed
unwrapin a test is the failure you want. - Provably infallible operations. Use
expectand state why it can't fail.
use std::net::IpAddr;
fn main() {
let ip: IpAddr = "127.0.0.1"
.parse()
.expect("literal is a valid IP address");
println!("{ip}");
}The expect message states the invariant ("literal is a valid IP address"). It does not repeat the error ("parse failed"). When this panics, the message tells the next reader which assumption was wrong.
Document panics and offer a non-panicking twin
If a function panics on bad input, put a # Panics section in its doc comment. If callers might reasonably hold data of unknown quality, also provide a fallible version. The standard library pairs v[i] with v.get(i) for this reason.
/// Returns the average of `values`.
///
/// # Panics
///
/// Panics if `values` is empty.
pub fn mean(values: &[f64]) -> f64 {
assert!(!values.is_empty(), "mean called with an empty slice");
values.iter().sum::<f64>() / values.len() as f64
}
/// Returns the average of `values`, or `None` if it is empty.
pub fn try_mean(values: &[f64]) -> Option<f64> {
if values.is_empty() {
None
} else {
Some(mean(values))
}
}
fn main() {
println!("{:?}", try_mean(&[1.0, 2.0, 6.0]));
println!("{:?}", try_mean(&[]));
}This prints Some(3.0) and then None.
Parse once, then carry the proof in a type
The best way to reduce error handling is to validate at the boundary and encode the result in a type. After that, no function needs to re-check. Here Port can only be constructed through FromStr, so any Port you hold is already valid.
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Port(u16);
impl Port {
pub fn get(self) -> u16 {
self.0
}
}
#[derive(Debug, PartialEq, Eq)]
pub enum PortError {
NotANumber(ParseIntError),
Reserved(u16),
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortError::NotANumber(e) => write!(f, "port is not a number: {e}"),
PortError::Reserved(n) => write!(f, "port {n} is reserved"),
}
}
}
impl Error for PortError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
PortError::NotANumber(e) => Some(e),
PortError::Reserved(_) => None,
}
}
}
impl From<ParseIntError> for PortError {
fn from(e: ParseIntError) -> Self {
PortError::NotANumber(e)
}
}
impl FromStr for Port {
type Err = PortError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let n: u16 = s.trim().parse()?;
if n < 1024 {
return Err(PortError::Reserved(n));
}
Ok(Port(n))
}
}
fn main() {
for input in ["8080", "80", "abc"] {
match input.parse::<Port>() {
Ok(p) => println!("ok: {}", p.get()),
Err(e) => println!("error: {e}"),
}
}
}Implementing FromStr also gives callers the standard .parse::<Port>() entry point. If your conversion is not from text, implement TryFrom<T> instead.
Designing the error type
Libraries: be specific
A library should return an error type its callers can inspect. Follow these conventions:
- Use an enum with one variant per failure that callers might handle differently, as
PortErrordoes. - Implement
Display,Error, andFromfor the errors you wrap, so?works inside your crate. - Implement
source()to expose the underlying cause, and don't paste the cause's text into your own message as well. Error-reporting tools walk the chain, and duplicated text appears twice. - Consider
#[non_exhaustive]on public error enums. Adding a variant later is then not a breaking change. - Don't expose the types of your dependencies in your public errors unless you accept that upgrading them is a breaking change for you.
Applications: be convenient
An application usually just reports errors. Box<dyn Error> or a crate such as anyhow is enough, and main can return Result<(), Box<dyn Error>>. Specific enums pay off when your code must branch on the kind of error.
Message style
Error messages are written in lowercase, without a trailing period, so they compose in chains like config error: port 80 is reserved. Each layer describes only its own level and leaves the cause to source().
Common mistakes
- Using
unwrapto avoid designing an error. Everyunwrapon external input is a hidden crash. Convert it to?orexpectwith a stated invariant. - Returning
Result<T, String>. Strings can't be matched on, have nosource(), and don't implementError. Use an enum. - Swallowing errors.
.ok()andlet _ =discard the reason. Do that only when you have decided the failure doesn't matter, and leave a comment. - A single giant error enum for everything. If a function can fail in two ways, its error type should not list twenty. Split by module or operation.
- Panicking across a library boundary for convenience. Offer the fallible version first and a panicking convenience wrapper second, not the other way around.
- Using
Option<Result<T, E>>orResult<Option<T>, E>without thinking. Both are legitimate. For example,Result<Option<T>, E>means "the lookup can fail, and also may find nothing". Pick the nesting that matches how callers will handle it, and usetranspose()to swap it.
Exercises
Exercise
A function nth_word(text: &str, n: usize) returns the nth word of some text. Should it return Option<&str>, Result<&str, E>, or panic when there are fewer than n + 1 words? Justify your choice.
Show answer
Return Option<&str>. Having too few words is an ordinary outcome for arbitrary text, so a correct caller can hit it, which rules out panicking. There is only one reason for absence (not enough words), so Result would add an error type that carries no extra information. The name and signature make the meaning of None obvious.
Exercise
You are writing a library function load_config(path: &Path) that reads and parses a file. A teammate suggests Result<Config, String> to keep it simple. Give two concrete problems with that choice and say what to use instead.
Show answer
A String can't be matched on, so callers can't tell "file missing" from "invalid syntax" without parsing the text. It also doesn't implement Error and has no source(), so error-reporting tools can't show the underlying io::Error or parse error. Use a custom enum (for example with Io(io::Error) and Syntax(...) variants) that implements Display, Error, and From for the wrapped errors, and optionally mark it #[non_exhaustive].