Sub topic 10
Defining your own error type
This chapter assumes you know enums and match, the ? operator, and the basics of traits. Here you build an error type that fits your own program, so callers can tell failures apart.
Why a custom type
Returning ParseIntError or String works for small programs. But a function that can fail in several ways needs one error type that names each way. An enum does this well, because each variant is one kind of failure and can carry the data that explains it.
The three pieces
A useful error type needs three things:
#[derive(Debug)], whichErrorrequires and whichmainuses to print a returned error.impl fmt::Display, which gives a short message meant for people.impl std::error::Error, which marks the type as an error so it works withBox<dyn Error>and error-handling crates.
use std::error::Error;
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum ConfigError {
Missing(&'static str),
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, "bad number: {e}"),
}
}
}
impl Error for ConfigError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
ConfigError::BadNumber(e) => Some(e),
ConfigError::Missing(_) => None,
}
}
}
fn read_port(value: Option<&str>) -> Result<u16, ConfigError> {
let text = value.ok_or(ConfigError::Missing("port"))?;
text.parse::<u16>().map_err(ConfigError::BadNumber)
}
fn main() {
for input in [Some("8080"), Some("abc"), None] {
match read_port(input) {
Ok(port) => println!("port {port}"),
Err(e) => println!("error: {e}"),
}
}
}The program prints:
port 8080
error: bad number: invalid digit found in string
error: missing key: portHow the example fits together
ok_or turns the Option into a Result carrying ConfigError::Missing. The ? then returns that error early. For the parse step, map_err(ConfigError::BadNumber) passes the enum variant as a function. That wraps the ParseIntError in the right variant.
The empty impl Error is valid, because every method has a default. Here we override source, which reports the underlying cause. Tools that walk the chain of causes can then print the original ParseIntError too.
Common mistakes
- Forgetting
Debug. The compiler then rejects theimpl Errorblock. - Putting the full cause text in
Displayand also returning it fromsource. Reporting tools then print the cause twice. Pick one place. - Using
Stringvariants for everything. You lose the ability tomatchon the failure and read its data.
The next chapter shows how to implement From so that ? wraps ParseIntError for you, which removes the map_err call.
Exercise
Add a third variant, OutOfRange(u16), to ConfigError. Make read_port return it when the port is below 1024. What must you change besides the enum and read_port?
Show answer
Add an arm for OutOfRange to the match in Display, for example write!(f, "port {p} is below 1024"). The compiler requires it because match must be exhaustive. In source, the _ or Missing(_) arm must also cover the new variant, so use _ => None. In read_port, after parsing, return Err(ConfigError::OutOfRange(port)) when port < 1024.