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

Help: Sub Errors #364

Closed
snowfoxsh opened this issue Apr 10, 2024 · 3 comments
Closed

Help: Sub Errors #364

snowfoxsh opened this issue Apr 10, 2024 · 3 comments
Labels
question Further information is requested

Comments

@snowfoxsh
Copy link

In the readme file an example is shown of multiple sub errors being rendered under the main error message. How can I replicate this behavior?

x failed to find desired version
|> received some ~~~
|> missing field ~~~

Error

@zkat zkat added the question Further information is requested label Apr 10, 2024
@zkat
Copy link
Owner

zkat commented Apr 10, 2024

That's done through the standard Error::source. You can define this with thiserror by using #[source] on the field that holds the suberror. It's also automatically implemented if you use thiserror's #[from] field.

Additionally, in order to have those sub-errors get the miette treatment themselves, you can use #[source_diagnostic] along with #[source] or #[from] to get things like nested snippets, nested error codes, etc.

A full example:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Error, Diagnostic)]
struct JsonError {
  #[source]
  #[source_diagnostic]
  inner: SerdeJsonErrorWrapper
}

#[derive(Debug, Error, Diagnostic)]
struct SerdeJsonErrorWrapper(#[from] serde_json::Error);

(I've added an unnecessary indirection just to show #[source_diagnostic], since serde_json::Error is not a miette::Diagnostic).

@snowfoxsh
Copy link
Author

Thank you for your patience, that answers my question! Also, Is there a way to set the diagnostic code from with a variable in the sturct? Or can you inherit a code from structure in a field?

@zkat
Copy link
Owner

zkat commented Apr 10, 2024

Not with the current derive macro. You'd have to implement Diagnostic::code by hand, which is really not a ton of effort, just a bit less concise.

@zkat zkat closed this as completed Apr 10, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants