diff --git a/src/error/multiple_error_types/wrap_error.md b/src/error/multiple_error_types/wrap_error.md index e8acd25197..392b783aed 100644 --- a/src/error/multiple_error_types/wrap_error.md +++ b/src/error/multiple_error_types/wrap_error.md @@ -4,6 +4,7 @@ An alternative to boxing errors is to wrap them in your own error type. ```rust,editable use std::error; +use std::error::Error as _; use std::num::ParseIntError; use std::fmt; @@ -22,8 +23,10 @@ impl fmt::Display for DoubleError { match *self { DoubleError::EmptyVec => write!(f, "please use a vector with at least one element"), - // This is a wrapper, so defer to the underlying types' implementation of `fmt`. - DoubleError::Parse(ref e) => e.fmt(f), + // The wrapped error contains additional information and is available + // via the source() method. + DoubleError::Parse(..) => + write!(f, "the provided string could not be parsed as int"), } } } @@ -51,6 +54,8 @@ impl From for DoubleError { fn double_first(vec: Vec<&str>) -> Result { let first = vec.first().ok_or(DoubleError::EmptyVec)?; + // Here we implicitly use the `ParseIntError` implementation of `From` (which + // we defined above) in order to create a `DoubleError`. let parsed = first.parse::()?; Ok(2 * parsed) @@ -59,7 +64,12 @@ fn double_first(vec: Vec<&str>) -> Result { fn print(result: Result) { match result { Ok(n) => println!("The first doubled is {}", n), - Err(e) => println!("Error: {}", e), + Err(e) => { + println!("Error: {}", e); + if let Some(source) = e.source() { + println!(" Caused by: {}", source); + } + }, } }