Best practice of error messages in Display wrt error chaining

I'm looking for guidance and opinions on how best to format Display messages for error types that feature chained errors. I have seen and used both of the two approaches:

  1. For error variants that contain sub-domain error values, include the sub-error Display message into this error's formatting like so:

    MyError::Io(err) => write!("input/output error: {}", err)
  2. Output only information that pertains to this error's layer, relying on error chaining to provide the drill-down messages:

    MyError::Io(_) => write!("input/output error")

Some disadvantages of the first approach are that the message can grow excessively long if the nesting goes deep, and, should an error handler that displays or prints the message also output the chained errors, the chained messages are unnecessarily repeated. The second approach may result in too terse and uninformative messages if only Display is used to format the error, making consumers rely more on error chaining or Debug to reproduce the error information to full extent.

I tend to favor the second approach for the "don't repeat" principle and predictable message length. Should it be recommended as the best practice all around?

I ran into something similar recently with failure. I think the correct way is to not included the inner error, and to walk the chain to print more information. I think convenience methods for walking the chain for display purposes should be added.

1 Like