Struct darling_core::error::Error
source · pub struct Error { /* private fields */ }
Expand description
An error encountered during attribute parsing.
Given that most errors darling encounters represent code bugs in dependent crates, the internal structure of the error is deliberately opaque.
§Usage
Proc-macro expansion happens very infrequently compared to runtime tasks such as deserialization, and it happens in the context of an expensive compilation taks. For that reason, darling prefers not to fail on the first error it encounters, instead doing as much work as it can, accumulating errors into a single report.
As a result, darling::Error
is more of guaranteed-non-empty error collection
than a single problem. These errors also have some notion of hierarchy, stemming from
the hierarchical nature of darling’s input.
These characteristics make for great experiences when using darling-powered crates, provided crates using darling adhere to some best practices:
- Do not attempt to simplify a
darling::Error
into some other error type, such assyn::Error
. To surface compile errors, instead usedarling::Error::write_errors
. This preserves all span information, suggestions, etc. Wrapping adarling::Error
in a custom error enum works as-expected and does not force any loss of fidelity. - Do not use early return (e.g. the
?
operator) for custom validations. Instead, create anerror::Accumulator
to collect errors as they are encountered. Then useAccumulator::finish
to return your validated result; it will giveOk
if and only if no errors were encountered. This can create very complex custom validation functions; in those cases, split independent “validation chains” out into their own functions to keep the main validator manageable. - Use
darling::Error::custom
to create additional errors as-needed, then callwith_span
to ensure those errors appear in the right place. Usedarling::util::SpannedValue
to keep span information around on parsed fields so that custom diagnostics can point to the correct parts of the input AST.
Implementations§
source§impl Error
impl Error
Error creation functions
sourcepub fn duplicate_field(name: &str) -> Self
pub fn duplicate_field(name: &str) -> Self
Creates a new error for a field that appears twice in the input.
sourcepub fn duplicate_field_path(path: &Path) -> Self
pub fn duplicate_field_path(path: &Path) -> Self
Creates a new error for a field that appears twice in the input. Helper to avoid repeating the syn::Path to String conversion.
sourcepub fn missing_field(name: &str) -> Self
pub fn missing_field(name: &str) -> Self
Creates a new error for a non-optional field that does not appear in the input.
sourcepub fn unknown_field(name: &str) -> Self
pub fn unknown_field(name: &str) -> Self
Creates a new error for a field name that appears in the input but does not correspond to a known field.
sourcepub fn unknown_field_path(path: &Path) -> Self
pub fn unknown_field_path(path: &Path) -> Self
Creates a new error for a field name that appears in the input but does not correspond to a known field. Helper to avoid repeating the syn::Path to String conversion.
sourcepub fn unknown_field_with_alts<'a, T, I>(field: &str, alternates: I) -> Self
pub fn unknown_field_with_alts<'a, T, I>(field: &str, alternates: I) -> Self
Creates a new error for a field name that appears in the input but does not correspond to a known attribute. The second argument is the list of known attributes; if a similar name is found that will be shown in the emitted error message.
sourcepub fn unknown_field_path_with_alts<'a, T, I>(
field: &Path,
alternates: I,
) -> Self
pub fn unknown_field_path_with_alts<'a, T, I>( field: &Path, alternates: I, ) -> Self
Creates a new error for a field name that appears in the input but does not correspond to a known attribute. The second argument is the list of known attributes; if a similar name is found that will be shown in the emitted error message.
sourcepub fn unsupported_shape(shape: &str) -> Self
pub fn unsupported_shape(shape: &str) -> Self
Creates a new error for a struct or variant that does not adhere to the supported shape.
pub fn unsupported_shape_with_expected<T: Display>( shape: &str, expected: &T, ) -> Self
pub fn unsupported_format(format: &str) -> Self
sourcepub fn unexpected_type(ty: &str) -> Self
pub fn unexpected_type(ty: &str) -> Self
Creates a new error for a field which has an unexpected literal type.
pub fn unexpected_expr_type(expr: &Expr) -> Self
sourcepub fn unexpected_lit_type(lit: &Lit) -> Self
pub fn unexpected_lit_type(lit: &Lit) -> Self
Creates a new error for a field which has an unexpected literal type. This will automatically
extract the literal type name from the passed-in Lit
and set the span to encompass only the
literal value.
§Usage
This is most frequently used in overrides of the FromMeta::from_value
method.
use darling::{FromMeta, Error, Result};
use syn::{Lit, LitStr};
pub struct Foo(String);
impl FromMeta for Foo {
fn from_value(value: &Lit) -> Result<Self> {
if let Lit::Str(ref lit_str) = *value {
Ok(Foo(lit_str.value()))
} else {
Err(Error::unexpected_lit_type(value))
}
}
}
sourcepub fn unknown_value(value: &str) -> Self
pub fn unknown_value(value: &str) -> Self
Creates a new error for a value which doesn’t match a set of expected literals.
sourcepub fn too_few_items(min: usize) -> Self
pub fn too_few_items(min: usize) -> Self
Creates a new error for a list which did not get enough items to proceed.
sourcepub fn too_many_items(max: usize) -> Self
pub fn too_many_items(max: usize) -> Self
Creates a new error when a list got more items than it supports. The max
argument
is the largest number of items the receiver could accept.
sourcepub fn multiple(errors: Vec<Error>) -> Self
pub fn multiple(errors: Vec<Error>) -> Self
Bundle a set of multiple errors into a single Error
instance.
Usually it will be more convenient to use an error::Accumulator
.
§Panics
This function will panic if errors.is_empty() == true
.
sourcepub fn accumulator() -> Accumulator
pub fn accumulator() -> Accumulator
Creates an error collector, for aggregating multiple errors
See Accumulator
for details.
source§impl Error
impl Error
Error instance methods
sourcepub fn has_span(&self) -> bool
pub fn has_span(&self) -> bool
Check if this error is associated with a span in the token stream.
sourcepub fn with_span<T: Spanned>(self, node: &T) -> Self
pub fn with_span<T: Spanned>(self, node: &T) -> Self
Tie a span to the error if none is already present. This is used in darling::FromMeta
and other traits to attach errors to the most specific possible location in the input
source code.
All darling
-built impls, either from the crate or from the proc macro, will call this
when appropriate during parsing, so it should not be necessary to call this unless you have
overridden:
FromMeta::from_meta
FromMeta::from_nested_meta
FromMeta::from_value
sourcepub fn span(&self) -> Span
pub fn span(&self) -> Span
Get a span for the error.
§Return Value
This function will return Span::call_site()
if Self::has_span
is false
.
To get the span only if one has been explicitly set for self
, instead use Error::explicit_span
.
sourcepub fn explicit_span(&self) -> Option<Span>
pub fn explicit_span(&self) -> Option<Span>
Get the span for self
, if one has been set.
sourcepub fn flatten(self) -> Self
pub fn flatten(self) -> Self
Recursively converts a tree of errors to a flattened list.
§Child Diagnostics
If the diagnostics
feature is enabled, any child diagnostics on self
will be cloned down to all the errors within self
.
sourcepub fn at<T: Display>(self, location: T) -> Self
pub fn at<T: Display>(self, location: T) -> Self
Adds a location to the error, such as a field or variant. Locations must be added in reverse order of specificity.
sourcepub fn at_path(self, path: &Path) -> Self
pub fn at_path(self, path: &Path) -> Self
Adds a location to the error, such as a field or variant. Locations must be added in reverse order of specificity. This is a helper function to avoid repeating path to string logic.
sourcepub fn len(&self) -> usize
pub fn len(&self) -> usize
Gets the number of individual errors in this error.
This function never returns 0
, as it’s impossible to construct
a multi-error from an empty Vec
.
sourcepub fn add_sibling_alts_for_unknown_field<'a, T, I>(self, alternates: I) -> Self
pub fn add_sibling_alts_for_unknown_field<'a, T, I>(self, alternates: I) -> Self
Consider additional field names as “did you mean” suggestions for
unknown field errors if and only if the caller appears to be operating
at error’s origin (meaning no calls to Self::at
have yet taken place).
§Usage
flatten
fields in derived trait implementations rely on this method to offer correct
“did you mean” suggestions in errors.
Because the flatten
field receives all unknown fields, if a user mistypes a field name
that is present on the outer struct but not the flattened struct, they would get an incomplete
or inferior suggestion unless this method was invoked.
sourcepub fn write_errors(self) -> TokenStream
pub fn write_errors(self) -> TokenStream
Write this error and any children as compile errors into a TokenStream
to
be returned by the proc-macro.
The behavior of this method will be slightly different if the diagnostics
feature
is enabled: In that case, the diagnostics will be emitted immediately by this call,
and an empty TokenStream
will be returned.
Return these tokens unmodified to avoid disturbing the attached span information.
§Usage
// in your proc-macro function
let opts = match MyOptions::from_derive_input(&ast) {
Ok(val) => val,
Err(err) => {
return err.write_errors();
}
}
Trait Implementations§
source§impl Error for Error
impl Error for Error
source§fn description(&self) -> &str
fn description(&self) -> &str
source§fn cause(&self) -> Option<&dyn StdError>
fn cause(&self) -> Option<&dyn StdError>
source§impl Extend<Error> for Accumulator
impl Extend<Error> for Accumulator
source§fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = Error>,
fn extend<I>(&mut self, iter: I)where
I: IntoIterator<Item = Error>,
source§fn extend_one(&mut self, item: A)
fn extend_one(&mut self, item: A)
extend_one
)source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one
)Auto Trait Implementations§
impl Freeze for Error
impl RefUnwindSafe for Error
impl !Send for Error
impl !Sync for Error
impl Unpin for Error
impl UnwindSafe for Error
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
source§unsafe fn clone_to_uninit(&self, dst: *mut T)
unsafe fn clone_to_uninit(&self, dst: *mut T)
clone_to_uninit
)