Skip to content

Commit e6817b7

Browse files
committed
Add section about not including sources in Display impl
1 parent 1e3d0f9 commit e6817b7

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
@@ -272,7 +272,27 @@ be lowercase without trailing punctuation, and typically concise.
272272
[`Error::description()`] should not be implemented. It has been deprecated and users should
273273
always use `Display` instead of `description()` to print the error.
274274

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

277297
### Examples from the standard library
278298

0 commit comments

Comments
 (0)