Skip to content

Change span of as_dyn_error() to point compile error at attribute.#258

Merged
dtolnay merged 1 commit intodtolnay:masterfrom
de-vri-es:as-dyn-error-span
Oct 19, 2023
Merged

Change span of as_dyn_error() to point compile error at attribute.#258
dtolnay merged 1 commit intodtolnay:masterfrom
de-vri-es:as-dyn-error-span

Conversation

@de-vri-es
Copy link
Copy Markdown
Contributor

@de-vri-es de-vri-es commented Oct 19, 2023

This PR changes the span of the as_dyn_error() call to the #[source], #[from] or #[transparant] attribute if it exists.

My motivation was a (to me) confusing error that actually made me think thiserror had a bug:

use thiserror::Error;

#[derive(Debug, Error)]
#[error("{0}")]
enum Error {
    Io(#[from] std::io::Error),
    Custom(#[from] String),
}

image

The error uses the span of the source member, but in this case it is unnamed. How exactly it ends up with the span of the string literal is a bit unclear to me. Maybe because the member (0) is used in the formatting code?

Regardless, with this PR, the error is the same but the span is changed to the attribute:

image

If there was no #[source], #[from] or #[transparent] attribute, the member name is used as before (which in practise means it must be a member named source).

Copy link
Copy Markdown
Owner

@dtolnay dtolnay left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks!

@dtolnay dtolnay merged commit 4850c6f into dtolnay:master Oct 19, 2023
takumi-earth pushed a commit to earthlings-dev/thiserror that referenced this pull request Jan 27, 2026
Change span of `as_dyn_error()` to point compile error at attribute.
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

Successfully merging this pull request may close these issues.

2 participants