Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow #[error(transparent)] on fields #103

Open
djc opened this issue Oct 7, 2020 · 1 comment
Open

Allow #[error(transparent)] on fields #103

djc opened this issue Oct 7, 2020 · 1 comment

Comments

@djc
Copy link

djc commented Oct 7, 2020

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.

@pjenvey
Copy link

pjenvey commented Oct 27, 2023

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.

@dtolnay dtolnay changed the title Allow #[error(transparent)] on struct fields Allow #[error(transparent)] on fields Nov 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants