Sub topic 5
Wrapping other errors with #[from] and #[source]
This chapter assumes you know Rust enums, Result, the ? operator, and the basics of thiserror from the previous chapter. You should also know how to add a crate with Cargo.
Why wrap errors
A function often fails because a lower-level call failed. Reading a config file can fail with an std::io::Error. Parsing a port can fail with a ParseIntError. Your error type should keep that original error. If you throw it away, the caller loses the real reason for the failure.
Rust models this with the source method of std::error::Error. It returns the underlying cause, if there is one. Tools that print error chains follow source from one error to the next.
#[from]: wrap and convert
Mark a field with #[from] and thiserror does two things. It implements From<ParseIntError> for ConfigError, and it implements source to return that field.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
#[error("invalid port")]
InvalidPort(#[from] std::num::ParseIntError),
}
pub fn parse_port(s: &str) -> Result<u16, ConfigError> {
Ok(s.trim().parse::<u16>()?)
}The ? operator calls From::from on the error when it returns early. Here it turns a ParseIntError into ConfigError::InvalidPort. You write no map_err.
A variant with #[from] may hold only the wrapped error. It cannot carry other fields, because From::from receives one value and has nothing to fill the rest with.
#[source]: wrap without a conversion
Sometimes a variant needs extra data, such as the path of a file. Then you cannot use #[from]. Use #[source] on the cause and build the variant yourself.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ReadError {
#[error("could not read {path}")]
Read {
path: String,
#[source]
source: std::io::Error,
},
}
pub fn read_config(path: &str) -> Result<String, ReadError> {
std::fs::read_to_string(path).map_err(|source| ReadError::Read {
path: path.to_string(),
source,
})
}A field named source is treated as the source automatically. The attribute makes your intent explicit, and it is required when the field has another name.
| Attribute | Generates `From` | Generates `source` | Extra fields allowed |
|---|---|---|---|
| `#[from]` | Yes | Yes | No |
| `#[source]` | No | Yes | Yes |
Common errors
Two #[from] variants for the same type fail to compile. Two From<ParseIntError> impls would conflict. A port parse and a timeout parse that both fail with ParseIntError need #[source] and a map_err that picks the variant.
Putting the cause in the message duplicates it. If source returns the io::Error, a reporter prints it as the next line in the chain. Writing "could not read {path}: {source}" makes it appear twice. Keep each message about its own level.
#[from] is easy to overuse. A bare From<io::Error> means every I/O failure in the function becomes the same variant, whatever the cause. Prefer #[source] when context such as the path matters.
How the chain looks
The diagram below shows the chain for a failed read.
Exercise
You need a variant Parse { line: usize, source: ParseIntError } that records the line number. Can you use #[from] on source, and what should you write instead?
Show answer
No. #[from] generates From<ParseIntError>, which cannot supply line, so thiserror rejects extra fields. Use #[source] (or the field name source) and build the variant with map_err(|source| ConfigError::Parse { line, source }).
Exercise
Why does Ok(s.trim().parse::<u16>()?) compile in parse_port when the function returns Result<u16, ConfigError>?
Show answer
The ? operator calls From::from on the ParseIntError. #[from] on InvalidPort generated From<ParseIntError> for ConfigError, so the conversion exists.