Skip to content

Prevent duplicated error information in "wrapping errors" example #1375

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 28, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions src/error/multiple_error_types/wrap_error.md
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand All @@ -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"),
}
}
}
Expand Down Expand Up @@ -51,6 +54,8 @@ impl From<ParseIntError> for DoubleError {

fn double_first(vec: Vec<&str>) -> Result<i32> {
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::<i32>()?;

Ok(2 * parsed)
Expand All @@ -59,7 +64,12 @@ fn double_first(vec: Vec<&str>) -> Result<i32> {
fn print(result: Result<i32>) {
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);
}
},
}
}

Expand Down