Sub topic 3
Writing a custom error type by hand
This chapter builds a custom error enum without any helper crates. You need to know what each piece does before a derive macro writes it for you. I assume you are comfortable with enums, match, Result, the ? operator, and implementing traits.
Why define your own error type
Result<T, E> works with any E. Many programs start with Result<T, String> or Result<T, Box<dyn Error>>. Both break down as the code grows:
- A
Stringcarries a message but no structure. Callers cannot tell a missing key from a bad number without comparing text. - A
Box<dyn Error>hides the concrete type. Callers cannotmatchon what went wrong.
A custom enum gives each failure its own variant and its own data. Callers can match on variants, and you can change the messages without breaking them.
What a type needs to be an error
The std::error::Error trait has two supertraits, so a type needs three things before it is a full error:
Debug. Usually#[derive(Debug)]. This is the programmer-facing form, printed by{:?}and byunwrappanics.Display. A hand-written impl. This is the user-facing message, printed by{}.Error. Usually an empty impl, but you overridesourcewhen the error wraps another error.
A fourth piece, From, is optional. It lets ? convert a lower-level error into yours.
The complete example
This program defines ConfigError, implements every piece, and runs it.
use std::collections::HashMap;
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 lookup<'a>(config: &'a HashMap<&str, &str>, key: &str) -> Result<&'a str, ConfigError> {
config
.get(key)
.copied()
.ok_or_else(|| ConfigError::Missing(key.to_string()))
}
fn port_from_config(config: &HashMap<&str, &str>) -> Result<u16, ConfigError> {
let raw = lookup(config, "port")?;
parse_port(raw)
}
fn main() {
for input in ["8080", " 443 ", "abc", "70000"] {
match parse_port(input) {
Ok(port) => println!("ok: {port}"),
Err(e) => {
println!("error: {e}");
if let Some(cause) = e.source() {
println!(" caused by: {cause}");
}
}
}
}
let empty = HashMap::new();
if let Err(e) = port_from_config(&empty) {
println!("error: {e}");
}
}Running it prints:
ok: 8080
ok: 443
error: invalid port
caused by: invalid digit found in string
error: invalid port
caused by: number too large to fit in target type
error: missing key: portThe sections below take the pieces one at a time.
Debug: derive it
#[derive(Debug)] works because ParseIntError and String are both Debug. If a variant holds a type that is not Debug, the derive fails to compile, so that field type is the thing to fix.
Display: the message for people
Display::fmt writes into the formatter and returns fmt::Result. Use write! and return its result directly. A match on self with one arm per variant is the standard shape. The compiler checks that you covered every variant, so adding a variant later produces a compile error here until you write its message.
Write the message in lower case with no trailing period. Error messages often get joined into one line such as failed to start: invalid port: invalid digit found in string, and that convention keeps the line readable.
The InvalidPort arm ignores the inner error on purpose:
ConfigError::InvalidPort(_) => write!(f, "invalid port"),If this arm printed the ParseIntError text too, any code that walks the chain would show that text twice, once from this error and once from its source. The rule is that each error describes only its own level, and source exposes the level below.
Error: expose the cause
The Error impl can be empty (impl Error for MyError {}) when the error wraps nothing. When it does wrap something, override source:
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ConfigError::InvalidPort(e) => Some(e),
ConfigError::Missing(_) => None,
}
}Three details matter here:
- The return type is
Option<&(dyn Error + 'static)>. A reference to the inner error is a trait object, soSome(e)coerces&ParseIntErrorto&dyn Errorautomatically. - The
'staticbound applies to the type behind the reference, not to the borrow. It means the inner type holds no short-lived references. Your wrapped error types need to satisfy it. - Variants with no cause return
None. Forgetting the override is not a compile error. The defaultsourcereturnsNone, so the cause is silently lost from every chain report. This is the most common mistake in hand-written errors.
The trait also has older methods, description and cause. Both are deprecated. Do not implement them.
From: let ? do the conversion
The ? operator on a Result<T, E1> inside a function returning Result<U, E2> does this on failure: it calls From::from(e1) and returns Err with the converted value. So parse::<u16>()? compiles in parse_port only because From<ParseIntError> for ConfigError exists.
Without that impl you would see an error like `the trait From<ParseIntError> is not implemented for ConfigError `. You would fix it by adding the impl, or by converting manually:
fn parse_port_manual(s: &str) -> Result<u16, ConfigError> {
s.trim()
.parse::<u16>()
.map_err(ConfigError::InvalidPort)
}map_err(ConfigError::InvalidPort) works because a tuple variant is also a function from its field to the enum. This form needs no From impl, and it is the right tool when From would be wrong.
Notice that lookup(config, "port")? inside port_from_config needs no impl you wrote. The standard library provides impl<T> From<T> for T, so an error converts to its own type.
When a From impl is the wrong choice
A From impl maps one source type to exactly one variant. That causes two problems.
First, you cannot write two From<std::io::Error> impls for the same type, so two variants cannot both be built by ? from an io::Error. If your enum has ReadConfig and WriteCache variants that both wrap io::Error, use map_err at each call site and drop the From impl.
Second, From cannot add data. If a variant also records which file failed, there is nowhere to get the file name from inside from. Again, use map_err with a closure:
fn read_file(path: &str) -> Result<String, ReadError> {
std::fs::read_to_string(path).map_err(|source| ReadError {
path: path.to_string(),
source,
})
}This assumes a ReadError struct with path and source fields. The next chapters show how thiserror expresses this pattern.
Edge cases and gotchas
- Matching on a wrapped error.
match err { ConfigError::InvalidPort(inner) => ... }gives callers the concreteParseIntError. That makes the inner type part of your public API. If you later swap it for another type, downstream matches break. SendandSync. Errors that cross thread boundaries, or that you want to convert intoBox<dyn Error + Send + Sync>, need both. An enum isSend + Synconly when all its fields are. A variant holding anRc<str>quietly removes both.- Converting into
Box<dyn Error>. Any type implementingErrorconverts intoBox<dyn Error>through a standardFromimpl. Sofn main() -> Result<(), Box<dyn Error>>can use?onConfigErrorwith no extra code. unwrapandexpectshow Debug. A failedunwrap()prints theDebugform, so a derivedDebugshows variant names and nested fields. Your hand-writtenDisplaytext will not appear there.- Display is not for matching. If a caller must branch on the kind of failure, give them a variant. Do not ask them to compare
to_string()results.
What the hand-written version costs
Count the code for two variants. There is one enum, one Display match, one Error match, and one From impl. Each new variant adds an arm to Display, possibly an arm to source, and often a From impl. The compiler checks Display exhaustiveness, but source often uses a _ => arm in real code, so a new variant can silently report no cause.
That repeated, mechanical code is what thiserror generates. Because you wrote it by hand once, you can read what #[error], #[from], and #[source] expand into.
Exercise
Add a third variant, OutOfRange(u16), to ConfigError. It represents a port below 1024 and must have the message port 80 is reserved when the value is 80. Which three places in the code must change for the program to compile and behave correctly, and which of them can you forget without a compiler error?
Show answer
The three places are the enum definition, the Display match (add ConfigError::OutOfRange(p) => write!(f, "port {p} is reserved")), and the source match. The Display match is non-exhaustive without the new arm, so the compiler forces you to fix it. The source match in the example lists both existing variants explicitly, so it also fails to compile until you add ConfigError::OutOfRange(_) => None. If source had used a _ => None arm, you could have forgotten it with no error, and for a variant with a cause that would silently drop the cause. No From impl is needed, because OutOfRange is built by your own check, for example if port < 1024 { return Err(ConfigError::OutOfRange(port)); }, not by ? on a library error.
Exercise
A struct Store has two methods. One reads a file with std::fs::read_to_string and the other writes one with std::fs::write. Both return std::io::Error, and your error enum has variants Read(std::io::Error) and Write(std::io::Error). Why can you not write impl From<std::io::Error> for StoreError for both, and what do you write instead?
Show answer
Rust allows only one From<std::io::Error> impl per target type, and one impl can choose only one variant, so ? cannot tell whether the io::Error came from reading or writing. Write no From impl and convert at each call site with map_err: .map_err(StoreError::Read)? in the read method and .map_err(StoreError::Write)? in the write method.