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

Val err details #12

Merged
merged 19 commits into from
Jul 9, 2021
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ let mut u = Username::new(" valid name \n\n").unwrap();
assert_eq!(u.get(), "valid name"); // now we're talking!

// This also works for mutations:
assert!(matches!(u.try_mutate(|u| *u = " ".to_owned()), Err(prae::ValidationError)));
assert!(matches!(u.try_mutate(|u| *u = " ".to_owned()), Err(prae::ValidationError { .. })))
```

Now our `Username` trims provided value automatically.
Expand Down
1 change: 1 addition & 0 deletions prae/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,6 @@ prae_macro = { version = "0.2", path = "../prae_macro" }
serde = { version = "1.0", optional = true }

[dev-dependencies]
assert_matches = "1.5"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
29 changes: 18 additions & 11 deletions prae/src/core.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,30 @@
use core::hash::Hash;
use std::fmt;
use std::ops::{Deref, Index};
use std::{error::Error, fmt};

/// Default validation error. It is used for [`define!`](prae_macro::define) macro with `ensure`
/// keyword.
#[derive(PartialEq)]
pub struct ValidationError;

impl std::error::Error for ValidationError {}
/// Used for [`define!`](prae_macro::define) macro with `ensure` keyword.
#[derive(Clone, Debug)]
pub struct ValidationError {
/// The name of the type where this error originated.
type_name: &'static str,
}

impl fmt::Debug for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "provided value is not valid")
impl ValidationError {
/// Create a new error with the input value that failed.
pub fn new(type_name: &'static str ) -> Self {
ValidationError { type_name }
}
}

impl Error for ValidationError {}

impl fmt::Display for ValidationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "provided value is not valid")
write!(
f,
"failed to create {}: provided value is invalid",
self.type_name
)
}
}

Expand Down
Loading