diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs index 24d72f2b37..11e9fd07ea 100644 --- a/crates/common_utils/src/pii.rs +++ b/crates/common_utils/src/pii.rs @@ -11,9 +11,13 @@ use diesel::{ serialize::{Output, ToSql}, sql_types, AsExpression, }; +use error_stack::{IntoReport, ResultExt}; use masking::{Secret, Strategy, WithType}; -use crate::{errors::ValidationError, validation::validate_email}; +use crate::{ + errors::{self, ValidationError}, + validation::validate_email, +}; /// A string constant representing a redacted or masked value. pub const REDACTED: &str = "Redacted"; @@ -101,8 +105,17 @@ where serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Default, AsExpression, )] #[diesel(sql_type = diesel::sql_types::Text)] +#[serde(try_from = "String")] pub struct Email(Secret); +impl TryFrom for Email { + type Error = error_stack::Report; + + fn try_from(value: String) -> Result { + Self::from_str(&value).change_context(errors::ParsingError::EmailParsingError) + } +} + impl From> for Email { fn from(value: Secret) -> Self { Self(value) @@ -157,8 +170,7 @@ where } impl FromStr for Email { - type Err = ValidationError; - + type Err = error_stack::Report; fn from_str(email: &str) -> Result { if email.eq(REDACTED) { return Ok(Self(Secret::new(email.to_string()))); @@ -170,7 +182,8 @@ impl FromStr for Email { } Err(_) => Err(ValidationError::InvalidValue { message: "Invalid email address format".into(), - }), + }) + .into_report(), } } } @@ -247,15 +260,13 @@ mod pii_masking_strategy_tests { #[test] fn test_valid_newtype_email() { - let email_check: Result = - Email::from_str("example@abc.com"); + let email_check = Email::from_str("example@abc.com"); assert!(email_check.is_ok()); } #[test] fn test_invalid_newtype_email() { - let email_check: Result = - Email::from_str("example@abc@com"); + let email_check = Email::from_str("example@abc@com"); assert!(email_check.is_err()); }