Sub topic 3
Defining Your Own Error Type in Rust
Assume basic Rust syntax, enums, pattern matching, ownership, borrowing, and iterators. This chapter focuses on APIs that can fail.
Custom errors and automatic conversion
An application error enum gives callers meaningful failure cases. Implement Display for readable messages and Error to integrate with Rust’s error tools. Implement From when a lower-level error should become one of your variants.
use std::{error::Error, fmt, num::ParseIntError};
#[derive(Debug)]
enum ConfigError {
Missing(&'static str),
InvalidNumber(ParseIntError),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Missing(key) => write!(f, "missing configuration: {key}"),
Self::InvalidNumber(error) => write!(f, "invalid number: {error}"),
}
}
}
impl Error for ConfigError {}
impl From<ParseIntError> for ConfigError {
fn from(error: ParseIntError) -> Self {
Self::InvalidNumber(error)
}
}
fn read_port(value: Option<&str>) -> Result<u16, ConfigError> {
let text = value.ok_or(ConfigError::Missing("port"))?;
Ok(text.parse()?)
}
fn main() -> Result<(), Box<dyn Error>> {
println!("{}", read_port(Some("8080"))?);
Ok(())
}The ? operator uses From to convert ParseIntError into ConfigError. Box<dyn Error> is a flexible catch-all return type when callers do not need to match specific error variants.
Collecting results and options
An iterator of Result<T, E> values can become one Result<Vec<T>, E>. Collection stops at the first error. An iterator of Option<T> similarly becomes None if any item is missing.
| Input iterator | Collected result |
|---|---|
| `Ok(1), Ok(2)` | `Ok(vec![1, 2])` |
| `Ok(1), Err(e)` | `Err(e)` |
Ownership and API design
as_ref borrows the contained value, as_mut mutably borrows it, and take moves it out while leaving None.
fn main() {
let mut job = Some(String::from("ready"));
if let Some(text) = job.as_ref() {
println!("{text}");
}
if let Some(text) = job.as_mut() {
text.push('!');
}
let removed = job.take();
println!("{removed:?} {job:?}");
}Crates such as thiserror reduce custom error boilerplate. anyhow provides convenient application-level errors.
Return Result when callers can recover or need diagnostics. Return Option when absence is expected and needs no explanation. Use unwrap or expect only when failure proves a programming error or an invariant is guaranteed. Reserve panic! for unrecoverable bugs.
Exercise
What does take do to an Option<String>?
Show answer
It moves the string out and replaces the option with None.