@@ -4,6 +4,7 @@ An alternative to boxing errors is to wrap them in your own error type.
4
4
5
5
``` rust,editable
6
6
use std::error;
7
+ use std::error::Error as _;
7
8
use std::num::ParseIntError;
8
9
use std::fmt;
9
10
@@ -22,8 +23,10 @@ impl fmt::Display for DoubleError {
22
23
match *self {
23
24
DoubleError::EmptyVec =>
24
25
write!(f, "please use a vector with at least one element"),
25
- // This is a wrapper, so defer to the underlying types' implementation of `fmt`.
26
- DoubleError::Parse(ref e) => e.fmt(f),
26
+ // The wrapped error contains additional information and is available
27
+ // via the source() method.
28
+ DoubleError::Parse(..) =>
29
+ write!(f, "the provided string could not be parsed as int"),
27
30
}
28
31
}
29
32
}
@@ -51,6 +54,8 @@ impl From<ParseIntError> for DoubleError {
51
54
52
55
fn double_first(vec: Vec<&str>) -> Result<i32> {
53
56
let first = vec.first().ok_or(DoubleError::EmptyVec)?;
57
+ // Here we implicitly use the `ParseIntError` implementation of `From` (which
58
+ // we defined above) in order to create a `DoubleError`.
54
59
let parsed = first.parse::<i32>()?;
55
60
56
61
Ok(2 * parsed)
@@ -59,7 +64,12 @@ fn double_first(vec: Vec<&str>) -> Result<i32> {
59
64
fn print(result: Result<i32>) {
60
65
match result {
61
66
Ok(n) => println!("The first doubled is {}", n),
62
- Err(e) => println!("Error: {}", e),
67
+ Err(e) => {
68
+ println!("Error: {}", e);
69
+ if let Some(source) = e.source() {
70
+ println!(" Caused by: {}", source);
71
+ }
72
+ },
63
73
}
64
74
}
65
75
0 commit comments