Sub topic 9
Designing a Custom Error Type
This chapter assumes you can write match expressions and implement a trait for a type. It also assumes you know how ? returns early from a function that returns Result, and that ? converts errors through the From trait. Here you will use those pieces to build an error type for your own library or application code.
Why define your own error type
A function like read_port can fail in more than one way. The key may be missing, or the text may not be a number. Returning String loses the structure, so callers can only print the message. Returning ParseIntError hides the missing-key case. A custom error type is usually an enum with one variant per failure category. It gives callers three things:
- A single error type for the whole function or module, so
?works on every call inside it. - Variants the caller can match on to decide what to do.
- Control over the message shown to users and the cause reported to logs.
The four pieces
A custom error type that works well with ? needs four things:
- An
enum(or struct) holding the data for each failure, with#[derive(Debug)]. impl fmt::Display, which produces the human-readable message.impl std::error::Error, which marks the type as an error and optionally reports its cause.- One
impl From<SourceError>for each error type you want?to convert automatically.
The following program shows all four, plus a main that runs it.
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(String),
BadNumber(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::BadNumber(e) => write!(f, "invalid number: {e}"),
}
}
}
impl Error for ConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ConfigError::BadNumber(e) => Some(e),
ConfigError::Missing(_) => None,
}
}
}
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::BadNumber(e)
}
}
fn read_port(value: Option<&str>) -> Result<u16, ConfigError> {
let text = value.ok_or_else(|| ConfigError::Missing("port".to_string()))?;
let port = text.parse::<u16>()?;
Ok(port)
}
fn main() {
for input in [Some("8080"), Some("eighty"), None] {
match read_port(input) {
Ok(port) => println!("port = {port}"),
Err(e) => {
println!("error: {e}");
if let Some(cause) = e.source() {
println!(" caused by: {cause}");
}
}
}
}
}The output is:
port = 8080
error: invalid number: invalid digit found in string
caused by: invalid digit found in string
error: missing key: portNote that Error requires Debug and Display. If you leave either one out, the impl Error line fails to compile. The Error trait has default methods, so an empty impl Error for ConfigError {} is valid. You only write source when your error wraps another one.
How ? uses the type
In read_port, the line text.parse::<u16>()? produces a Result<u16, ParseIntError>. The function returns Result<u16, ConfigError>, so ? cannot return the ParseIntError as is. It calls From::from on the error, and your From<ParseIntError> implementation supplies the conversion.
The ok_or_else call on the previous line belongs to the same design. A missing value is an Option::None, which carries no error. ok_or_else builds the ConfigError::Missing value only when it is needed, and then ? returns it. Its error type is already ConfigError, so the From conversion is the identity conversion and costs nothing.
Choosing variants
Design variants around what a caller might do differently, not around which function failed internally. These guidelines help:
- Add a variant when a caller might reasonably react to it, for example by retrying, using a default, or showing a specific message.
- Store the data needed to explain the failure, such as the key name or the path. Do not store a pre-formatted sentence. Formatting belongs in
Display. - Wrap a lower-level error when you want to preserve its details. Keep it as a field so
source()can return it. - Avoid a catch-all
Other(String)variant early on. It tends to collect every failure nobody planned for, and callers cannot match on it usefully.
Public enums can also gain variants over time. If your library is published, mark the enum with #[non_exhaustive] so adding a variant does not break downstream match expressions.
Exposing the cause with source
Display should describe the failure at this level. source() returns the underlying error. Tools that print an error chain, such as the {:?} output of some reporters, walk source() to show each layer.
There is a choice to make about duplication. In the example above, Display for BadNumber includes the inner message (invalid number: invalid digit found in string), and source() also returns the inner error. A reporter that prints both would show the cause twice. The convention is to pick one:
- Include the cause in
Displayif callers will print only the top-level error. - Leave it out of
Displayand expose it throughsource()if a reporter prints the whole chain.
Either is acceptable. Be consistent within one crate.
When From is not enough
From has a limit. You can write only one impl From<ParseIntError> for ConfigError, so every ParseIntError becomes the same variant. Suppose a function parses both a port and a timeout, and you want to know which one failed. Use map_err to attach context and construct the variant yourself. Then ? receives an error that is already your type.
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum SettingsError {
BadPort { text: String, source: ParseIntError },
BadTimeout { text: String, source: ParseIntError },
}
impl fmt::Display for SettingsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
SettingsError::BadPort { text, .. } => write!(f, "invalid port {text:?}"),
SettingsError::BadTimeout { text, .. } => write!(f, "invalid timeout {text:?}"),
}
}
}
impl Error for SettingsError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
SettingsError::BadPort { source, .. } => Some(source),
SettingsError::BadTimeout { source, .. } => Some(source),
}
}
}
#[derive(Debug)]
struct Settings {
port: u16,
timeout_secs: u32,
}
fn parse_settings(port_text: &str, timeout_text: &str) -> Result<Settings, SettingsError> {
let port = port_text
.parse::<u16>()
.map_err(|source| SettingsError::BadPort {
text: port_text.to_string(),
source,
})?;
let timeout_secs = timeout_text
.parse::<u32>()
.map_err(|source| SettingsError::BadTimeout {
text: timeout_text.to_string(),
source,
})?;
Ok(Settings { port, timeout_secs })
}
fn main() {
println!("{:?}", parse_settings("8080", "30"));
match parse_settings("8080", "soon") {
Ok(s) => println!("{s:?}"),
Err(e) => println!("error: {e}"),
}
}This prints Ok(Settings { port: 8080, timeout_secs: 30 }) and then error: invalid timeout "soon". This version has no From implementation at all. That is a legitimate design. Use From when one source type maps to one meaning, and map_err when the meaning depends on where the error occurred.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Missing `From` for a source error | `?` cannot convert the error: the trait `From<X>` is not implemented for your type | Add `impl From<X> for YourError`, or use `map_err` |
| Missing `Debug` derive | `Error` impl fails because `Debug` is not satisfied | Add `#[derive(Debug)]` |
| Two `From` impls for the same source type | Conflicting implementations error | Keep one, and use `map_err` for the other meaning |
| Returning `Box<dyn Error>` where callers need to match | Callers must downcast to inspect the failure | Return the enum from library code |
| Cause printed twice | Error reports repeat the same text | Choose either `Display` or `source()` for the inner message |
Custom enum or Box<dyn Error>
Prefer a custom enum when other code will inspect the error, which is typical for libraries and for modules with distinct recovery paths. Prefer Box<dyn Error> for small programs where the only action on failure is to print it. The next chapter covers Box<dyn Error> in detail. A common pattern is to use enums inside your library and Box<dyn Error> at the top of the binary that calls it.
Exercise
A function load(path: &str) -> Result<u32, LoadError> calls std::fs::read_to_string(path)? and then text.trim().parse::<u32>()?. Define LoadError with variants for both failures so that both ? operators compile, and explain why no map_err is needed.
Show answer
Define enum LoadError { Io(std::io::Error), Parse(std::num::ParseIntError) } with #[derive(Debug)], implement Display and Error (returning the inner error from source), and add impl From<std::io::Error> for LoadError { fn from(e: std::io::Error) -> Self { LoadError::Io(e) } } and impl From<std::num::ParseIntError> for LoadError { fn from(e: std::num::ParseIntError) -> Self { LoadError::Parse(e) } }. No map_err is needed because each source error type appears once, so each has exactly one From implementation. ? finds the matching one from the error type of the expression.
Exercise
Why does parse_settings in this chapter use map_err instead of impl From<ParseIntError> for SettingsError?
Show answer
Both the port and the timeout fail with the same type, ParseIntError. A From implementation can produce only one variant for that type, so the code could not tell BadPort from BadTimeout. map_err runs at the call site, where the code knows which field it was parsing, and it can add the offending text.