Sub topic 9
Display for error types
This chapter assumes you know how impl Trait for Type works, how Result and ? behave at a basic level, and the difference between {} and {:?} in format strings. You have already seen Display on ordinary types. Here you apply it to errors, where the text is shown to people who did not write the code.
Why errors need Display
An error type has two audiences. The programmer reads Debug output to see the exact structure. The person running the program reads Display output to learn what went wrong and what to do next.
derive(Debug) gives you the first for free. There is no derive(Display), because the standard library cannot guess a sentence for your type. You write it yourself, usually with one match arm per variant.
A Display implementation per variant
The PortError type below has two failure modes. Display turns each one into a short sentence.
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),
}
}
}
fn main() {
let a = PortError::OutOfRange(70000);
let b = PortError::Parse("abc".parse::<i64>().unwrap_err());
println!("{}", a);
println!("{:?}", a);
println!("{}", b);
println!("{:?}", b);
}This prints:
port 70000 is out of range
OutOfRange(70000)
not a number: invalid digit found in string
Parse(ParseIntError { kind: InvalidDigit })The match has no wildcard arm. If you add a variant later, the compiler refuses to build until you write its message. That is the main reason to prefer a match over a single generic message.
Writing good messages
The Rust API guidelines and the standard library settle on a few conventions:
- Start with a lowercase letter and end without a period. Messages are often embedded in longer ones, such as
failed to load config: port 70000 is out of range. - Use one line. Do not put
\nin the message. - Include the offending value when it helps, as
OutOfRangedoes withn. - Say what happened, not what type it is.
port 70000 is out of rangeis better thanPortError::OutOfRange.
Becoming a real error with std::error::Error
A type that implements Display and Debug can be promoted to a full error by implementing std::error::Error. The trait requires both of those as supertraits, so the work from the previous sections is a prerequisite. The trait has no required methods, so an empty impl is enough:
impl std::error::Error for PortError {}Once the type implements Error, it converts into Box<dyn Error>. That lets functions with different error types share one return type, and ? does the conversion.
Wrapped errors and source()
PortError::Parse holds another error. Error::source exposes it, so callers can walk the chain of causes. When you do this, avoid printing the inner message twice. A common rule is that an error either includes its source in its own Display text or returns it from source(), not both. In the program below, Display describes only this layer and source() carries the detail.
use std::error::Error;
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(_) => write!(f, "port is not a number"),
PortError::OutOfRange(n) => write!(f, "port {} is out of range", n),
}
}
}
impl Error for PortError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
PortError::Parse(e) => Some(e),
PortError::OutOfRange(_) => None,
}
}
}
fn parse_port(s: &str) -> Result<u16, PortError> {
let n: i64 = s.trim().parse().map_err(PortError::Parse)?;
u16::try_from(n).map_err(|_| PortError::OutOfRange(n))
}
fn report(e: &dyn Error) {
println!("error: {}", e);
let mut cause = e.source();
while let Some(c) = cause {
println!(" caused by: {}", c);
cause = c.source();
}
}
fn main() {
for input in ["8080", "abc", "70000"] {
match parse_port(input) {
Ok(p) => println!("port {}", p),
Err(e) => report(&e),
}
}
}The output is:
port 8080
error: port is not a number
caused by: invalid digit found in string
error: port 70000 is out of rangeThis version uses map_err(PortError::Parse) instead of a From implementation. The From route, where ? converts the error automatically, is covered in its own chapter. Both approaches work with the same Display code.
Display versus Debug when main returns an error
main can return Result<(), E> when E: Debug. If it returns Err, the runtime prints the error using Debug, not Display. Users then see the raw structure:
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let n: i32 = "abc".parse()?;
println!("{}", n);
Ok(())
}This prints Error: ParseIntError { kind: InvalidDigit } to standard error and exits with a non-zero status. If you want a readable message, catch the error yourself and print it with {}:
fn main() {
if let Err(e) = run() {
eprintln!("error: {}", e);
std::process::exit(1);
}
}
fn run() -> Result<(), Box<dyn std::error::Error>> {
let n: i32 = "abc".parse()?;
println!("{}", n);
Ok(())
}Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Calling `self.to_string()` inside `fmt` | Infinite recursion, because `to_string` calls `fmt` | Use `write!(f, ...)` with the fields |
| Using `{}` on a type with only `Debug` | Compile error: `doesn't implement Display` | Implement `Display` or print with `{:?}` |
| Repeating the source message in both `Display` and `source()` | The same text appears twice in error reports | Pick one place |
| Ending messages with a period or newline | Chained messages look broken | Follow the lowercase, no-period convention |
| Writing a wildcard `_` arm in the `match` | New variants silently get a generic message | List every variant |
Summary
- Derive
Debugfor developers and writeDisplayby hand for people who read the message. - A
matchover the variants gives each failure its own sentence and lets the compiler flag missing ones. - Implement
std::error::ErroronceDisplayandDebugexist, and return wrapped errors fromsource(). - Remember that
mainandunwrapuseDebug, so print with{}yourself when you want the friendly text.
Exercise
Add a variant Reserved(u16) to PortError in the source() example, for ports below 1024. What must you change so the program compiles, and what should source() return for it?
Show answer
Add an arm to the match in Display, for example PortError::Reserved(p) => write!(f, "port {} is reserved", p), and an arm in source(). Both matches lack wildcards, so the compiler rejects the code until each handles the new variant. source() should return None for Reserved, because it does not wrap another error. Optionally, parse_port should return Err(PortError::Reserved(p)) when the converted port is below 1024.