Sub topic 10
Defining your own error type
This chapter assumes you can write a Rust enum and match on it, you know what a trait is and how to implement one, and you have used ? and map_err on a Result. Error conversion with From gets its own chapter. Here you will only see it in passing.
Why a library or app needs its own error
Functions in the standard library return their own error types, such as ParseIntError. Your function may fail for several unrelated reasons: a missing key, a bad number, a value out of range. A Result<u16, E> has only one E, so you need one type that can describe all of those cases.
A custom error type gives you three things:
- Callers can
matchon the failure kind and react differently to each. - Each variant can carry the data needed to explain the failure.
- Your public API does not expose the error types of the crates you use internally.
The three requirements
A type is a well-behaved error when it implements these traits.
| Trait | Purpose | How you get it |
|---|---|---|
| `Debug` | Developer-facing output, used by `{:?}` and by `main` when it returns `Err` | `#[derive(Debug)]` |
| `Display` | User-facing message, used by `{}` | Write it by hand |
| `std::error::Error` | Marks the type as an error and links to an underlying cause | `impl Error for T {}` |
Error has Debug + Display as supertraits, so you cannot implement it without the other two. All of its methods have default bodies, so an empty impl is valid.
An error enum
An enum fits best when there are several distinct failure kinds. Each variant holds only the data that kind needs.
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(&'static str),
BadNumber(ParseIntError),
OutOfRange { value: u16, min: u16 },
}
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, "bad number: {e}"),
ConfigError::OutOfRange { value, min } => {
write!(f, "port {value} is below the minimum {min}")
}
}
}
}
impl Error for ConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ConfigError::BadNumber(e) => Some(e),
_ => None,
}
}
}
fn read_port(value: Option<&str>) -> Result<u16, ConfigError> {
let text = value.ok_or(ConfigError::Missing("port"))?;
let port = text
.trim()
.parse::<u16>()
.map_err(ConfigError::BadNumber)?;
if port < 1024 {
return Err(ConfigError::OutOfRange { value: port, min: 1024 });
}
Ok(port)
}
fn main() {
for input in [Some("8080"), None, Some("abc"), Some("80")] {
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 program prints:
port 8080
error: missing key: port
error: bad number: invalid digit found in string
caused by: invalid digit found in string
error: port 80 is below the minimum 1024Three details are worth noting.
map_err(ConfigError::BadNumber)uses the variant as a function. A tuple variant is a function from its field to the enum, so no closure is needed.source()returns the lower-level error that caused this one. OnlyBadNumberwraps another error, so every other variant returnsNone.- The
Displaytext forBadNumberalready includes the inner message, which is why "caused by" repeats it. Choose one of two conventions. Either the message includes the cause, as here, or the message describes only this level and the caller walkssource()to print the chain. Do not do both in a real program, or the output repeats.
Display messages and Debug output
Write Display messages for the person running the program. By convention they start in lowercase and have no trailing period or newline, so they compose well when chained as "failed to start: bad number: invalid digit found in string".
Keep Debug derived. When main returns Err, Rust prints the Debug form, which for this enum looks like BadNumber(ParseIntError { kind: InvalidDigit }). That output is meant for developers.
A struct error for a single failure kind
If every failure has the same shape, a struct is simpler than an enum.
use std::error::Error;
use std::fmt;
#[derive(Debug)]
struct LineError {
line: usize,
message: String,
}
impl fmt::Display for LineError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "line {}: {}", self.line, self.message)
}
}
impl Error for LineError {}
fn check(lines: &[&str]) -> Result<(), LineError> {
for (i, text) in lines.iter().enumerate() {
if text.trim().is_empty() {
return Err(LineError {
line: i + 1,
message: String::from("blank line"),
});
}
}
Ok(())
}
fn main() {
println!("{:?}", check(&["a", "b"]));
if let Err(e) = check(&["a", "", "c"]) {
println!("{e}");
}
}The output is Ok(()) followed by line 2: blank line. The impl Error for LineError {} body is empty because there is no underlying cause to report.
Letting ? do the wrapping
The map_err call in read_port can be removed. If you implement From<ParseIntError> for ConfigError, the ? operator converts the error for you.
impl From<ParseIntError> for ConfigError {
fn from(e: ParseIntError) -> Self {
ConfigError::BadNumber(e)
}
}With that impl in place, text.trim().parse::<u16>()? compiles and produces ConfigError::BadNumber. The next chapter covers this mechanism in detail.
Gotchas and edge cases
- Forgetting
Display. The compiler reports thatConfigErrordoes not implementDisplaywhen you writeimpl Error for ConfigError {}. The fix is to implementDisplay, not to remove theErrorimpl. source()and lifetimes. The signature must beOption<&(dyn Error + 'static)>. If a variant holds a type that borrows data, it cannot be returned here. Store owned data in error types, such asStringinstead of&str.&'static strfields.Missing(&'static str)works only for string literals. If the key name is computed at runtime, useString.- Large variants. A
Resultis as large as its biggest error variant. If one variant stores a large struct, consider boxing it so everyOkreturn does not carry that size. - Adding variants later. Adding a variant to a public enum breaks downstream code that matches it exhaustively. Mark a public enum
#[non_exhaustive]if you expect it to grow. Callers then need a wildcard arm. - Hiding internals. A variant like
BadNumber(ParseIntError)makesParseIntErrorpart of your public API. If that matters, store aStringmessage or use a private inner type.
Writing the boilerplate faster
The Display and From impls above are mechanical. Crates such as thiserror generate them from attributes on the enum, and a later chapter covers them. Write one by hand first, so you know what the macro produces.
Exercise
Add a variant Empty to ConfigError that means the port string was empty after trimming. Which three places in the code must change so the program still compiles and reports it correctly, and what does source() return for it?
Show answer
(1) Add Empty to the enum. (2) Add a ConfigError::Empty => write!(f, "port is empty") arm to the match in Display::fmt, because that match is exhaustive and fails to compile without it. (3) Return Err(ConfigError::Empty) from read_port when text.trim().is_empty(), before parsing. source() needs no edit because its _ => None arm already covers Empty, and None is correct since there is no underlying error.