Error::source, From, ?
pub trait Error: Debug + Display {
fn source(&self) -> Option<&(dyn Error + 'static)> { ... }
}
pub trait From<T>: Sized {
fn from(value: T) -> Self;
}Implement Error and From so ? can convert a leaf error into an application error, then walk source() for the cause.
| Parameter | Description |
|---|---|
value | From::from is what ? uses to convert the Err type of a callee into the Err type of the caller. |
Returns: source returns Option<&(dyn Error + 'static)>. From::from returns the converted error. ? either yields the success value or returns early with the converted error.
- The Option and Result page shows map_err and the requirement that the enclosing function return a compatible Result. This example relies on From instead of map_err.
- Call source through the Error trait, which must be in scope: use std::error::Error.
- description and cause on the Error trait are deprecated provided methods; new code should use Display and source.
use std::error::Error;
#[derive(Debug)]
struct ParsePortError;
impl std::fmt::Display for ParsePortError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "invalid port")
}
}
impl Error for ParsePortError {}
#[derive(Debug)]
enum AppError {
Parse(ParsePortError),
}
impl std::fmt::Display for AppError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AppError::Parse(err) => write!(f, "parse error: {err}"),
}
}
}
impl Error for AppError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
AppError::Parse(err) => Some(err),
}
}
}
impl From<ParsePortError> for AppError {
fn from(value: ParsePortError) -> Self {
AppError::Parse(value)
}
}
fn load() -> Result<(), AppError> {
Err(ParsePortError)?;
Ok(())
}
fn main() {
match load() {
Err(err) => {
println!("display={err}");
println!("source={:?}", err.source().map(|s| s.to_string()));
}
Ok(()) => println!("unexpected ok"),
}
}Expected output
display=parse error: invalid port
source=Some("invalid port")Related: Option and Result page, The ? operator