thiserror
thiserror copied to clipboard
Allow #[error(transparent)] on struct fields
The crate I'm currently working on has code like the following:
#[derive(Debug, Clone, Error)]
pub struct Error {
pub(crate) kind: ErrorKind,
backtrack: Option<ExtBacktrace>,
}
#[derive(Debug, Error)]
pub enum ErrorKind {
// error variants go here
}
If I understand correctly, this doesn't currently allow the Error
impl for Error
to return types from the ErrorKind
variants, which seems like it would be useful. I thought I might try #[error(transparent)]
on Error
's kind
field, but that's not allowed. Is there currently a way to support this scenario? From the description of error(transparent)
it seems like it would be a good fit for this, but maybe there's a good reason not to allow this.
This style was common with the failure
crate: it recommended it as one of its patterns as it simplifies handling of extra data like the Optional backtrace here in to one centralized place (rather than within each Kind
's variants).
I also came across this problem hoping #[error(transparent)]
might defer the top level Error's source
method to the inner kind
's. The solution was to simply not use thiserror::Error
for the top level Error
struct here, instead implementing custom std Error
and Display
traits for it that defer to kind
's.
#[derive(thiserror::Error)]
is not doing a lot for the top level Error in this case otherwise: those two traits are just a few lines of code. I just use #[derive(thiserror::Error)]
on the ErrorKind
which is where it's doing the heavier lifting.