Sub topic 9
Display for error types
This chapter assumes you know how to implement a trait with impl Trait for Type, how match works on enums, and the basics of Result. You should also have seen Display on a simple struct. Here you apply it to errors.
Why errors need Display
An error type has two audiences. A developer reads Debug output in logs and test failures. A user reads Display output in a message such as error: port 70000 is out of range.
Rust's std::error::Error trait requires both. A type that implements Error must also implement Debug and Display. You usually derive Debug and write Display by hand, because only you know what a good message says.
An error enum with Display
An enum is the usual shape for an error, with one variant per way the operation can fail. Implement Display with a match on self, and write one message per variant.
use std::fmt;
use std::num::ParseIntError;
#[derive(Debug)]
enum PortError {
Parse(ParseIntError),
OutOfRange(i64),
}
impl fmt::Display for PortError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
PortError::Parse(e) => write!(f, "not a number: {}", e),
PortError::OutOfRange(n) => write!(f, "port {} is out of range", n),
}
}
}
impl From<ParseIntError> for PortError {
fn from(e: ParseIntError) -> Self {
PortError::Parse(e)
}
}
fn parse_port(s: &str) -> Result<u16, PortError> {
let n: i64 = s.trim().parse()?;
u16::try_from(n).map_err(|_| PortError::OutOfRange(n))
}
fn main() {
println!("{:?}", parse_port("8080"));
match parse_port("abc") {
Ok(p) => println!("port {}", p),
Err(e) => println!("error: {}", e),
}
if let Err(e) = parse_port("70000") {
println!("error: {}", e);
}
}The match has no wildcard arm. If you add a variant later, the compiler refuses to build until you write its message.
The Parse arm shows a common pattern. It formats the wrapped error with {}, so the inner error's own Display text becomes part of yours. The From impl and the ? operator are covered in a later chapter. For now, note that ? lets parse_port return PortError while the standard library produces a ParseIntError.
Writing good messages
Follow the conventions the standard library uses:
- Start with a lowercase letter and leave off the final period. Messages often get chained, as in
error: not a number: invalid digit found in string. - Say what went wrong and include the offending value, as in
port 70000 is out of range. - Do not repeat the word "error" in the message. The code that prints it usually adds a prefix.
- Keep it to one line. Put extra detail in
Debugor in a separate source error.
What each trait shows
For PortError::OutOfRange(70000), the two traits give different output:
| Format | Trait | Output |
|---|---|---|
| `{}` | `Display` | `port 70000 is out of range` |
| `{:?}` | `Debug` | `OutOfRange(70000)` |
If main returns Result<(), PortError> and an error escapes, Rust prints it with Debug, not Display. For polished messages, print the error yourself with {}.
Exercise
You add a variant Reserved(u16) to PortError, for ports below 1024. You change nothing else. What happens when you compile, and what do you have to add?
Show answer
The build fails with a non-exhaustive patterns error in Display::fmt, because the match does not cover Reserved. Add an arm such as PortError::Reserved(p) => write!(f, "port {} is reserved", p).