Skip to content

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

Open

Description

@djc

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.

Activity

  1. pjenvey commented on Oct 27, 2023

    @pjenvey

    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.

  2. changed the title [-]Allow #[error(transparent)] on struct fields[/-] [+]Allow #[error(transparent)] on fields[/+] on Nov 5, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions