custom_error icon indicating copy to clipboard operation
custom_error copied to clipboard

[new feature] Attribute support on error enum's fields

Open Passeriform opened this issue 5 years ago • 3 comments

Currently, enum variants defined by custom_error! macro do not support attributes.

custom_error! {pub FooError
	IO {source: std::io::Error} = "IO operations failed unexpectedly.",
	#[cfg(feature = "use-mpsc")]
	MpscRecv {source: std::sync::mpsc::RecvError} = "Unexpected Mpsc receive error occured.",
}

This does not work.

The expected value from this addition comes from an extended support for features. A dependency from a feature can be included and an error variant can be added when compiling the crate conditionally.

Passeriform avatar Aug 08 '20 01:08 Passeriform

The alternative workaround for the time being is to define duplicate custom errors giving them each different condition externally:

#[cfg(feature = "use-mpsc")]
custom_error! {pub FooError
	IO {source: std::io::Error} = "IO operations failed unexpectedly.",
	MpscRecv {source: std::sync::mpsc::RecvError} = "Unexpected Mpsc receive error occured.",
}

#[cfg(not(feature = "use-mpsc"))]
custom_error! {pub FooError
	IO {source: std::io::Error} = "IO operations failed unexpectedly.",
}

It smells but works fine for now. I think this should be documented somewhere as well.

Passeriform avatar Aug 08 '20 01:08 Passeriform

Hello! Attributes are already supported on enum fields. However, they are not repeated in the match arms of code that implements traits for your errors. The compilation error occurs when you are removing a field using an attribute, but custom-error tries to match on this field to implement the Error trait on your type.

Would repeating the attributes in the match arms never make the code invalid, no matter what the attribute is? If so, then I would be open to meeting a PR that does that.

lovasoa avatar Aug 12 '20 21:08 lovasoa

This seems to be the case. I've tested it out in isolation now. The enum fields definitely follow the attributes. Its the implementation of traits that raises the issue, specifically Error and Display. They, in their current state, do not seem to follow the attributes.

I've created a gist for clarity purposes here.

I'm not quite sure if repeating attributes is going to remain valid for all cases but I hardly think one would want their attributes, defined on enum, not be reflected in the implementation of error traits. If that case ever arises, that may lead to more complexity (and quite possibly, issues) based on how the attributes are handled.

I'd love to work on this but I severely lack the experience with macros. Moreover, I think there is a need for elaboration on what kinds of attributes could potentially cause issues and if its implementation is viable.

Passeriform avatar Aug 13 '20 04:08 Passeriform