Sub topic 5
Wrapping other errors with #[from] and #[source]
This chapter assumes you can write a Rust enum, use ? in a function that returns Result, and add a crate with Cargo. It also assumes you know the thiserror basics from the previous chapter: #[derive(Error)] and #[error("...")]. Here you will learn how to make your error type hold the lower-level error that caused it, and how ? can do that conversion for you.
Why wrap an error at all
A function such as read_config can fail for several reasons. The file may be missing, the bytes may not be valid UTF-8, or a number inside may not parse. Each failure produces a different standard library error type: std::io::Error, ParseIntError, and so on.
Your function has one return type, so you need one error type that can represent all of these. You create an enum with one variant per failure and store the original error inside the variant. This is called wrapping.
Wrapping preserves the original cause. Your own message ("could not read config.toml") says what your program was doing. The wrapped error says why it failed ("permission denied"). A good report shows both.
The source() method
The std::error::Error trait has an optional method named source:
fn source(&self) -> Option<&(dyn std::error::Error + 'static)>It returns the underlying cause, or None if there is none. Calling source() repeatedly gives you a chain of errors, from the outermost to the innermost. By default source() returns None, so a wrapper that does not override it hides its cause from reporting tools.
Writing that override by hand is the boilerplate you saw earlier. The two thiserror attributes in this chapter generate it.
#[source]: mark the cause
#[source] on a field tells thiserror to return that field from source().
use thiserror::Error;
#[derive(Debug, Error)]
pub enum StoreError {
#[error("could not open {path}")]
Open {
path: String,
#[source]
source: std::io::Error,
},
}Two points apply here.
- A field named
sourceis treated as the source automatically, so the#[source]attribute is optional in this example. Writing it makes the intent explicit. If you name the field anything else, such ascause, the attribute is required. #[source]does not create aFromimpl. You construct the variant yourself, which lets you add thepathfield.
The source field's type must implement std::error::Error and be 'static. A Box<dyn std::error::Error + Send + Sync + 'static> also works when you want to hide the concrete type.
#[from]: mark the cause and generate From
#[from] does everything #[source] does and also generates impl From<ThatType> for YourError. That From impl is what the ? operator uses.
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("invalid port")]
InvalidPort(#[from] std::num::ParseIntError),
}With this in place, a function returning Result<_, ConfigError> can apply ? directly to a Result<_, ParseIntError>:
fn parse_port(s: &str) -> Result<u16, ConfigError> {
Ok(s.trim().parse::<u16>()?)
}When parse fails, ? calls ConfigError::from(parse_int_error). That produces ConfigError::InvalidPort(...), and the function returns it.
{{DIAGRAM_PLACEHOLDER}}
How ? converts the error
The ? operator does not know about thiserror. It only requires that the function's error type implements From<E> for the error type E of the expression. #[from] supplies that impl.
Rules for #[from]
#[from] has constraints that #[source] does not.
| Attribute | Generates `source()` | Generates `From` | Other fields allowed in the variant |
|---|---|---|---|
| `#[source]` | Yes | No | Yes |
| `#[from]` | Yes | Yes | No (only an optional backtrace) |
The reason for the second constraint is that From::from receives only the source error. It has nowhere to get a path or any other value, so the variant cannot have extra fields.
A second constraint follows from how Rust resolves trait impls. An enum can have only one #[from] for a given source type. Two #[from] std::io::Error variants would generate two conflicting impl From<std::io::Error> blocks, and the code would not compile.
Using both in one enum
The usual design uses #[from] for simple cases where one source type means one failure, and #[source] where you need extra context. This is the full example from the topic:
use std::error::Error;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("missing key: {0}")]
Missing(String),
#[error("invalid port")]
InvalidPort(#[from] std::num::ParseIntError),
#[error("could not read {path}")]
Read {
path: String,
#[source]
source: std::io::Error,
},
}
pub fn parse_port(s: &str) -> Result<u16, ConfigError> {
Ok(s.trim().parse::<u16>()?)
}
pub fn read_config(path: &str) -> Result<String, ConfigError> {
std::fs::read_to_string(path).map_err(|source| ConfigError::Read {
path: path.to_string(),
source,
})
}
fn print_chain(err: &dyn Error) {
println!("error: {err}");
let mut current = err.source();
while let Some(cause) = current {
println!(" caused by: {cause}");
current = cause.source();
}
}
fn main() {
let err = parse_port("abc").unwrap_err();
print_chain(&err);
let err = read_config("/no/such/file").unwrap_err();
print_chain(&err);
}On Linux this prints:
error: invalid port
caused by: invalid digit found in string
error: could not read /no/such/file
caused by: No such file or directory (os error 2)The Read variant is built with map_err, not ?. It has no From impl because it carries a path, so you must say explicitly where the error is wrapped. Missing has no source, so source() returns None for it.
Because ConfigError has no variant with a bare #[from] std::io::Error, a stray ? on an I/O call inside a ConfigError function will not compile. That is a useful safeguard, because it forces you to attach the path.
What the macro writes for you
For InvalidPort(#[from] ParseIntError), thiserror generates code equivalent to the hand-written version:
impl From<std::num::ParseIntError> for ConfigError {
fn from(e: std::num::ParseIntError) -> Self {
ConfigError::InvalidPort(e)
}
}
// inside impl std::error::Error for ConfigError:
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
ConfigError::InvalidPort(e) => Some(e),
ConfigError::Read { source, .. } => Some(source),
ConfigError::Missing(_) => None,
}
}Knowing this helps when a compiler error mentions a missing From impl or a trait bound on the source.
Common mistakes
Printing the source twice
Suppose you write #[error("invalid port: {0}")] on a variant that also has #[from]. The Display output now includes the cause, and source() also exposes it. A reporter that walks the chain prints the cause twice:
error: invalid port: invalid digit found in string
caused by: invalid digit found in stringPick one. The current convention is for Display to describe only the current level and let the chain supply the rest.
Losing context with a blanket #[from]
#[derive(Debug, Error)]
pub enum AppError {
#[error("I/O error")]
Io(#[from] std::io::Error),
}Every ? on any I/O call now becomes AppError::Io. The error says "I/O error" with no file name, so you cannot tell which operation failed. Use #[from] only when the source type alone identifies the failure. Otherwise use #[source] plus a field, as Read does.
Two variants, one source type
If Open and Write both wrap std::io::Error, both must use #[source], not #[from]. Each is constructed explicitly with map_err, which is also the only way to give them different messages.
Forwarding with transparent
When a variant exists only to pass an error through, #[error(transparent)] forwards both Display and source() to the inner error, so the wrapper adds no message of its own:
#[derive(Debug, Error)]
pub enum ConfigError {
#[error(transparent)]
Io(#[from] std::io::Error),
}Note that source() then returns the inner error's source, not the inner error itself. The wrapper is invisible in the chain.
Summary
source()links an error to its cause. Reporting tools walk this chain.#[source]exposes a field as the cause and leaves construction to you.#[from]exposes the cause and generatesFrom, which lets?convert errors automatically. The variant can have no other fields.- Each source type can appear in
#[from]only once per enum. - Keep
Displayfocused on the current level so that the chain does not repeat itself.
Exercise
A variant is declared as Parse { line: usize, #[from] source: std::num::ParseIntError }. Why does this fail to compile, and how do you fix it so the line number is kept?
Show answer
#[from] generates From<ParseIntError>, and From::from receives only the source error, so it cannot supply line. A variant with #[from] may have no other fields. Change #[from] to #[source] (the field is already named source), then build the variant with map_err(|source| ConfigError::Parse { line, source }).
Exercise
Given enum E { A(#[from] std::io::Error), B(#[from] std::io::Error) }, what goes wrong, and what is the minimal change that lets both variants exist?
Show answer
Both variants generate impl From<std::io::Error> for E, so the impls conflict and the code does not compile. The minimal change is to use #[source] on at least one variant (usually both) and give each a named field, such as A { path: String, #[source] source: std::io::Error }. Then construct each variant explicitly with map_err. Only one variant may keep #[from].
Exercise
Your Display for InvalidPort is "invalid port: {0}" and the variant uses #[from]. A reporter that prints every error in the chain shows the parse message twice. What are two ways to fix it?
Show answer
Either remove {0} from the message, so it reads "invalid port" and the chain supplies the cause, or keep the detailed message and stop exposing the cause (for example, store it in a field without #[source] or #[from]). The first is the usual choice because it keeps the cause available for downcasting and reporting.