Nutype 0.5.0 with custom errors #177
greyblake
announced in
Announcements
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Changes
error
andwith
attributes.lazy_static
withstd::sync::LazyLock
for regex validation. This requires Rust 1.80 or higher and may cause compilation issues on older Rust versions due to the use ofstd::sync::LazyLock
. If upgrading Rust isn't an option, you can still uselazy_static
explicitly as a workaround.::new()
constructor has been fully replaced by::try_new()
.Highlights
Custom errors
Previously, custom validation logic in nutype could be achieved by passing a
predicate
attribute, as shown below:This would automatically generate a simple error type:
However, this approach often lacked flexibility. Many users needed more detailed error handling. For example, some users wanted to attach additional information to errors or provide more descriptive error messages. Others preferred to use a single error type across their application, but found it cumbersome to map very specific errors to a more general error type.
To address these needs, nutype now introduces the
with
attribute for custom validation functions and theerror
attribute for specifying custom error types:With this enhancement, users have full control over the error type and how errors are constructed during validation, making the error handling process more powerful and adaptable to different use cases.
Transition from fallible
::new()
to::try_new()
In version 0.4.3, the fallible
::new()
constructor was deprecated but still available. Now, it has been fully replaced by::try_new()
. For example, to initialize aName
from the previous example:This change ensures a more consistent and explicit error-handling approach when creating instances.
Note that
::new()
is still used as a non-fallible constructor if there a newtype has no validation.This discussion was created from the release Nutype 0.5.0 with custom errors.
Beta Was this translation helpful? Give feedback.
All reactions