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

Add meaningful error messages #105

Closed
russellbanks opened this issue Nov 20, 2023 · 3 comments
Closed

Add meaningful error messages #105

russellbanks opened this issue Nov 20, 2023 · 3 comments

Comments

@russellbanks
Copy link

russellbanks commented Nov 20, 2023

Without using nutype, I use the thiserror crate to create Error types and give them relevant error messages:

#[derive(Error, Debug, PartialEq)]
pub enum PackageVersionError {
    #[error(
        "Package version length must be between {} and {} characters",
        PackageVersion::MIN_LENGTH,
        PackageVersion::MAX_LENGTH
    )]
    InvalidLength,
    #[error("Package version may not contain whitespace")]
    ContainsWhitespace,
    #[error("Package version may not contain any control characters")]
    ContainsControlChars,
    #[error(
        "Package version may not contain any of the following characters: {:?}",
        PackageVersion::DISALLOWED_CHARACTERS
    )]
    DisallowedCharacters,
}

Currently, trying to achieve a similar thing with nutype will just return error messages like "too short". This isn't helpful as I show the error to the user.

#[nutype(
    sanitize(trim),
    validate(
        not_empty,
        char_len_min = 4,
        char_len_max = 128,
    ),
    default = "",
    derive(AsRef, Clone, Default, Deref, Display, FromStr, Deserialize, Serialize),
)]

Ideally, I'd like for nutype's error to instead say something like Value is too short. The value length must be between 4 and 128 characters, or the same message but have a value name, such as Package version in my case.

@russellbanks
Copy link
Author

russellbanks commented Nov 20, 2023

It's a similar issue when providing a custom predicate; the function can only return a bool so we lose any meaningful reasoning for the error.

@greyblake
Copy link
Owner

greyblake commented Nov 22, 2023

@russellbanks Thanks for reporting this!

@greyblake
Copy link
Owner

This was recently addressed in #125
And will be released in 0.4.1.
If you need this earlier please ping me I can release a beta.

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

No branches or pull requests

2 participants