Skip to content

Commit 8a708f9

Browse files
committed
Add section about not including sources in Display impl
1 parent 7894a48 commit 8a708f9

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

src/interoperability.md

+20
Original file line numberDiff line numberDiff line change
@@ -273,7 +273,27 @@ The message given by [`Error::description()`] does not matter. Users should
273273
always use `Display` instead of `description()` to print the error. A low-effort
274274
description like `"JSON error"` is sufficient.
275275

276+
If an error type returns an underlying source error from [`Error::source()`], it does **not**
277+
include that source error in its own `Display` representation as well. This avoids duplicated
278+
information when an error is printed along with all its sources:
279+
280+
```rust
281+
use std::fmt;
282+
283+
impl fmt::Display for ParseError {
284+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285+
// Good errors never duplicate information like this:
286+
write!(f, "failed to parse: {}", self.source),
287+
288+
// Instead they just describe themselves:
289+
write!(f, "failed to parse"),
290+
}
291+
}
292+
```
293+
276294
[`Error::description()`]: https://doc.rust-lang.org/std/error/trait.Error.html#tymethod.description
295+
[`Error::source()`]: https://doc.rust-lang.org/std/error/trait.Error.html#method.source
296+
277297

278298
### Examples from the standard library
279299

0 commit comments

Comments
 (0)