Sub topic 1
Custom Error Types in Rust with thiserror and anyhow
Prerequisites
This chapter assumes basic Rust syntax, enums, pattern matching, traits, Result, and Cargo dependencies.
Result and the `?` Operator: A Quick Refresher
Result<T, E> represents either success (Ok(T)) or failure (Err(E)). The ? operator returns the error early when an operation fails.
For ? to work across different error types, Rust needs a conversion from the inner error to the function's error type. The From trait provides that conversion.
flowchart TD
A["parse::<u16>() returns Result"] --> B{"Ok or Err?"}
B -->|Ok| C["Continue with the value"]
B -->|Err| D["? calls From to convert the error"]
D --> E["Return Err from the function"]What Makes a Type an Error
A useful error type usually implements three traits:
Debugsupports developer-focused output and is commonly derived.Displayprovides a readable message for users.std::error::Erroridentifies the type as a standard Rust error and can expose an underlying cause.
The Error trait's source method connects an outer error to the error that caused it.
Writing a Custom Error Type by Hand
An enum can describe the failures a function may return. Hand-written implementations are explicit but verbose.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(String),
InvalidPort(ParseIntError),
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Missing(key) => write!(f, "missing key: {key}"),
Self::InvalidPort(_) => write!(f, "invalid port"),
}
}
}
impl std::error::Error for ConfigError {}
impl From<ParseIntError> for ConfigError {
fn from(error: ParseIntError) -> Self {
Self::InvalidPort(error)
}
}
fn parse_port(text: &str) -> Result<u16, ConfigError> {
Ok(text.trim().parse()?)
}The From implementation lets ? convert ParseIntError into ConfigError.
Removing the Boilerplate with `thiserror`
The thiserror crate generates the routine implementations while keeping the error enum strongly typed.
use thiserror::Error;
#[derive(Debug, Error)]
enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
#[error("invalid port")]
InvalidPort(#[from] std::num::ParseIntError),
}#[error] generates Display. The #[from] attribute generates both From<ParseIntError> and an error source.
Wrapping Other Errors with `#[from]` and `#[source]`
Use #[from] when a variant contains only the source error. Use #[source] when the variant also needs context, such as a file path.
#[derive(Debug, Error)]
enum ReadError {
#[error("could not read {path}")]
File {
path: String,
#[source]
source: std::io::Error,
},
}This preserves the original I/O error while adding information about which file failed.
Exercise
Why does parse_port need From<ParseIntError> for ConfigError?
Show answer
The ? operator uses that conversion when parsing returns ParseIntError.