#[implicit] fields for automatic data collection when building errors using From<source> #402
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This PR adds a new field attribute called
#[implicit]
. When applied to a field, this attribute causes the derivedFrom
implementation to initialize the field using a newImplicitField
trait. This trait and attribute is inspiried by the snafu crate. It can be used to automatically derive details such as a backtrace or the location of the error.Using this field is easy. First implement
ImplicitField
for your type:Then simply add the field to your Error struct or enum variant along with the
#[implicit]
attribute:Two important notes:
#[implicit]
fields require a sibling#[from]
field.#[implicit]
fields are only auto-generated in the derivedFrom
implementation. If you create your error another way you will have to initialize the field yourself.For more comprehensive usage examples including generating Location and Backtrace see this test: https://github.com/carlsverre/thiserror/blob/5195f7ccfa403af3741fd7381ceabd68705426b7/src/implicit.rs
The motivation behind this PR is this blog post https://greptime.com/blogs/2024-05-07-error-rust along with the other feature requests for Location and non-nightly Backtrace support. While
snafu
can be used for this, it has a much larger surface area thanthiserror
and may not be suitable for all projects. This PR shows that with a small change tothiserror
we can make the library more flexible without too much additional specialization.If @dtolnay is interested in this feature being polished and landed, I'm happy to put in additional work to make it happen. In addition to more testing and documentation, I suggest that this feature could eventually replace the existing Backtrace/provides code:
error_generic_member_access
is available (currently only in nightly) we could provide#[implicit]
fields by type. If multiple fields match, we could raise an error and have an explicit option on the implicit field.