Sub topic 3
Writing a custom error type by hand
This chapter assumes you know enums, match, Result, and traits. You should also know how ? returns early from a function. Here you build an error type with only the standard library. Doing it once by hand shows what thiserror generates for you in the next chapter.
The four pieces
A useful error enum needs four things:
- A
Debugimplementation, usually from#[derive(Debug)]. - A
Displayimplementation that writes a message for people. - An
impl std::error::Error, which marks the type as an error and can expose its cause. - A
Fromimplementation for each error type you want?to convert automatically.
The Error trait requires Debug + Display. Without those two, the Error impl does not compile.
The complete example
The enum has two variants. Missing carries the name of a config key. InvalidPort wraps the ParseIntError that caused the failure.
use std::error::Error;
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 {
ConfigError::Missing(key) => write!(f, "missing key: {key}"),
ConfigError::InvalidPort(_) => write!(f, "invalid port"),
}
}
}
impl Error for ConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ConfigError::InvalidPort(e) => Some(e),
ConfigError::Missing(_) => None,
}
}
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::InvalidPort(e)
}
}
fn parse_port(s: &str) -> Result<u16, ConfigError> {
Ok(s.trim().parse::<u16>()?)
}
fn require(key: &str, value: Option<&str>) -> Result<String, ConfigError> {
value
.map(str::to_string)
.ok_or_else(|| ConfigError::Missing(key.to_string()))
}
fn main() {
if let Err(e) = require("host", None) {
println!("error: {e}");
}
match parse_port("abc") {
Ok(port) => println!("port {port}"),
Err(e) => {
println!("error: {e}");
if let Some(cause) = e.source() {
println!("caused by: {cause}");
}
}
}
}Running it prints:
error: missing key: host
error: invalid port
caused by: invalid digit found in stringWhat each piece does
Display is the message a user sees. Keep it short and describe only this layer. InvalidPort does not repeat the parse error's text, because the cause is available separately through source.
source returns the underlying error, or None if there is none. The return type is Option<&(dyn Error + 'static)>, a reference to any error type behind a trait object. Reporting code can then follow the links from the outer error down to the root cause. A later chapter covers that.
From is what makes ? work. In parse_port, parse::<u16>() returns Result<u16, ParseIntError>. The function returns Result<u16, ConfigError>, so ? calls ConfigError::from on the error before returning it.
Common mistakes
- Forgetting
use std::error::Errorwhen callinge.source(). The method belongs to the trait, so the trait must be in scope. - Including the cause's text in
Displayand also returning it fromsource. A reporter that prints the whole chain then shows the same message twice. - Writing two
Fromimpls that wrap different errors in the same variant.?then cannot tell which context applies, so usemap_errfor those cases.
Why this gets tedious
For two variants the code runs to about 30 lines of boilerplate. Each new variant touches Display, source, and usually From. These are mechanical edits, and it is easy to forget one. The Display arm, the source arm, and the From impl must all stay in sync. That is the problem thiserror solves, and it is the subject of the next chapter.
Exercise
Add a variant OutOfRange(u16) to ConfigError for ports below 1024. Which of the four pieces must you update, and does source need a Some arm for it?
Show answer
Update Display with a new arm, for example ConfigError::OutOfRange(p) => write!(f, "port {p} is reserved"). Update source with ConfigError::OutOfRange(_) => None, because the match must be exhaustive and this variant wraps no other error. No From impl is needed, since no other error type converts into it. Debug is derived, so it needs no change.