feat: FromStr derive could support setting the error type#380
feat: FromStr derive could support setting the error type#380Peternator7 merged 3 commits intoPeternator7:masterfrom
Conversation
|
This looks really good! Sorry for the delay reviewing it |
| pub fn missing_parse_err_attr_error() -> syn::Error { | ||
| syn::Error::new( | ||
| Span::call_site(), | ||
| "`parse_err_ty` and `parse_err_fn` attribute is both required.", |
There was a problem hiding this comment.
| "`parse_err_ty` and `parse_err_fn` attribute is both required.", | |
| "`parse_err_ty` and `parse_err_fn` attributes are both required.", |
|
Please reconsider using string literals for paths. Attributes nowadays support arbitrary expressions (including paths) instead of only string literals. One of the authors of |
@sebschrader So you want like this? #[derive(Debug, EnumString)]
#[strum(
parse_err_fn = crate::custom::some_enum_not_found_err,
parse_err_ty = crate::custom::CaseCustomParseErrorNotFoundError
)]
enum CaseCustomParseErrorEnum {
#[strum(serialize = "red")]
Red,
#[strum(serialize = "blue")]
Blue,
}
mod custom {
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
struct CaseCustomParseErrorNotFoundError(String);
impl std::fmt::Display for CaseCustomParseErrorNotFoundError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
writeln!(f, "not found `{}`", self.0)
}
}
impl std::error::Error for CaseCustomParseErrorNotFoundError {}
pub fn some_enum_not_found_err(s: &str) -> CaseCustomParseErrorNotFoundError {
CaseCustomParseErrorNotFoundError(s.to_string())
}
} |
|
@sebschrader, I think it's a reasonable point. I've opened #410 to change this behavior since it's not released yet. |
Resolves #112 Related to #396 Add support for a `#[from_str(error(error_ty[, error_fn]))]` attribute to specify a custom error type for `FromStr` derive for enums (or structs with no fields) in case where the string does not match any variant. A conversion function to convert a `derive_more::FromStrError` to the custom error type might optionally be provided. Otherwise the custom error type `T` must satisfy `derive_more::FromStrError: Into<T>`. [`strum`](https://github.com/Peternator7/strum) provides similar functionality. See Peternator7/strum#380. This approach could be used to set a custom error type for `TryInto` derive as well (#396). Co-authored-by: Kai Ren <[email protected]> Co-authored-by: Jelte Fennema-Nio <[email protected]>
resolve #91 #332 #221
PR checker failed because #381