Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
refactor(errors): add parsing error types for context info (#911)
Sampras Lopes0d4669050240
diff --git a/crates/common_utils/src/errors.rs b/crates/common_utils/src/errors.rsindex e3f00799e0..de776954e7 100644--- a/crates/common_utils/src/errors.rs+++ b/crates/common_utils/src/errors.rs@@ -8,36 +8,23 @@///pub type CustomResult<T, E> = error_stack::Result<T, E>;-macro_rules! impl_error_display {- ($st: ident, $arg: tt) => {- impl std::fmt::Display for $st {- fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- fmt.write_str(&format!(- "{{ error_type: {:?}, error_description: {} }}",- self, $arg- ))- }- }- };-}--macro_rules! impl_error_type {- ($name: ident, $arg: tt) => {- #[doc = ""]- #[doc = stringify!(Error variant $name)]- #[doc = stringify!(Custom error variant for $arg)]- #[doc = ""]- #[derive(Debug)]- pub struct $name;-- impl_error_display!($name, $arg);-- impl std::error::Error for $name {}- };+/// Parsing Errors+#[derive(Debug, thiserror::Error)]+pub enum ParsingError {+ ///Failed to parse enum+ #[error("Failed to parse enum: {0}")]+ EnumParseFailure(&'static str),+ ///Failed to parse struct+ #[error("Failed to parse struct: {0}")]+ StructParseFailure(&'static str),+ /// Failed to encode data to given format+ #[error("Failed to serialize to {0} format")]+ EncodeError(&'static str),+ /// Failed to parse data+ #[error("Unknown error while parsing")]+ UnknownError,}-impl_error_type!(ParsingError, "Parsing error");-/// Validation errors.#[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented#[derive(Debug, thiserror::Error)]diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rsindex 912d859c01..82553f41bc 100644--- a/crates/common_utils/src/ext_traits.rs+++ b/crates/common_utils/src/ext_traits.rs@@ -85,10 +85,12 @@ whereResult<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,{- serde_json::to_string(&P::try_from(self).change_context(errors::ParsingError)?)- .into_report()- .change_context(errors::ParsingError)- .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))+ serde_json::to_string(+ &P::try_from(self).change_context(errors::ParsingError::UnknownError)?,+ )+ .into_report()+ .change_context(errors::ParsingError::EncodeError("string"))+ .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))}fn convert_and_url_encode(&'e self) -> CustomResult<String, errors::ParsingError>@@ -97,10 +99,12 @@ whereResult<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,{- serde_urlencoded::to_string(&P::try_from(self).change_context(errors::ParsingError)?)- .into_report()- .change_context(errors::ParsingError)- .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))+ serde_urlencoded::to_string(+ &P::try_from(self).change_context(errors::ParsingError::UnknownError)?,+ )+ .into_report()+ .change_context(errors::ParsingError::EncodeError("url-encoded"))+ .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))}// Check without two functions can we combine this@@ -110,7 +114,7 @@ where{serde_urlencoded::to_string(self).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::EncodeError("url-encoded")).attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))}@@ -120,7 +124,7 @@ where{serde_json::to_string(self).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::EncodeError("json")).attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))}@@ -130,7 +134,7 @@ where{serde_json::to_value(self).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::EncodeError("json-value")).attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))}@@ -140,7 +144,7 @@ where{serde_json::to_vec(self).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::EncodeError("byte-vec")).attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))}}@@ -152,13 +156,19 @@ pub trait BytesExt {////// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize`///- fn parse_struct<'de, T>(&'de self, type_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_struct<'de, T>(+ &'de self,+ type_name: &'static str,+ ) -> CustomResult<T, errors::ParsingError>whereT: Deserialize<'de>;}impl BytesExt for bytes::Bytes {- fn parse_struct<'de, T>(&'de self, _type_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_struct<'de, T>(+ &'de self,+ type_name: &'static str,+ ) -> CustomResult<T, errors::ParsingError>whereT: Deserialize<'de>,{@@ -166,7 +176,7 @@ impl BytesExt for bytes::Bytes {serde_json::from_slice::<T>(self.chunk()).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::StructParseFailure(type_name)).attach_printable_lazy(|| {let variable_type = std::any::type_name::<T>();format!("Unable to parse {variable_type} from bytes {self:?}")@@ -181,19 +191,25 @@ pub trait ByteSliceExt {////// Convert `[u8]` into type `<T>` by using `serde::Deserialize`///- fn parse_struct<'de, T>(&'de self, type_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_struct<'de, T>(+ &'de self,+ type_name: &'static str,+ ) -> CustomResult<T, errors::ParsingError>whereT: Deserialize<'de>;}impl ByteSliceExt for [u8] {- fn parse_struct<'de, T>(&'de self, type_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_struct<'de, T>(+ &'de self,+ type_name: &'static str,+ ) -> CustomResult<T, errors::ParsingError>whereT: Deserialize<'de>,{serde_json::from_slice(self).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::StructParseFailure(type_name)).attach_printable_lazy(|| format!("Unable to parse {type_name} from &[u8] {:?}", &self))}}@@ -205,13 +221,13 @@ pub trait ValueExt {////// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`///- fn parse_value<T>(self, type_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>whereT: serde::de::DeserializeOwned;}impl ValueExt for serde_json::Value {- fn parse_value<T>(self, type_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>whereT: serde::de::DeserializeOwned,{@@ -221,7 +237,7 @@ impl ValueExt for serde_json::Value {);serde_json::from_value::<T>(self).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::StructParseFailure(type_name)).attach_printable_lazy(|| debug)}}@@ -230,7 +246,7 @@ impl<MaskingStrategy> ValueExt for Secret<serde_json::Value, MaskingStrategy>whereMaskingStrategy: Strategy<serde_json::Value>,{- fn parse_value<T>(self, type_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>whereT: serde::de::DeserializeOwned,{@@ -245,7 +261,7 @@ pub trait StringExt<T> {////// Convert `String` into type `<T>` (which being an `enum`)///- fn parse_enum(self, enum_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError>whereT: std::str::FromStr,// Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`@@ -254,30 +270,36 @@ pub trait StringExt<T> {////// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`///- fn parse_struct<'de>(&'de self, type_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_struct<'de>(+ &'de self,+ type_name: &'static str,+ ) -> CustomResult<T, errors::ParsingError>whereT: Deserialize<'de>;}impl<T> StringExt<T> for String {- fn parse_enum(self, enum_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError>whereT: std::str::FromStr,<T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,{T::from_str(&self).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::EnumParseFailure(enum_name)).attach_printable_lazy(|| format!("Invalid enum variant {self:?} for enum {enum_name}"))}- fn parse_struct<'de>(&'de self, type_name: &str) -> CustomResult<T, errors::ParsingError>+ fn parse_struct<'de>(+ &'de self,+ type_name: &'static str,+ ) -> CustomResult<T, errors::ParsingError>whereT: Deserialize<'de>,{serde_json::from_str::<T>(self).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::StructParseFailure(type_name)).attach_printable_lazy(|| {format!("Unable to parse {type_name} from string {:?}", &self)})diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rsindex 6429d2f84f..c283ee575a 100644--- a/crates/redis_interface/src/commands.rs+++ b/crates/redis_interface/src/commands.rs@@ -133,7 +133,7 @@ impl super::RedisConnectionPool {pub async fn get_and_deserialize_key<T>(&self,key: &str,- type_name: &str,+ type_name: &'static str,) -> CustomResult<T, errors::RedisError>whereT: serde::de::DeserializeOwned,@@ -380,7 +380,7 @@ impl super::RedisConnectionPool {&self,key: &str,field: &str,- type_name: &str,+ type_name: &'static str,) -> CustomResult<V, errors::RedisError>whereV: serde::de::DeserializeOwned,diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rsindex 2221f5c758..c5d160adc6 100644--- a/crates/router/src/connector/adyen.rs+++ b/crates/router/src/connector/adyen.rs@@ -735,7 +735,8 @@ fn get_webhook_object_from_body(.notification_items.drain(..).next()- .ok_or(errors::ParsingError)+ // TODO: ParsingError doesn't seem to be an apt error for this case+ .ok_or(errors::ParsingError::UnknownError).into_report()?;Ok(item_object.notification_request_item)diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex 6b017b99eb..89d51908cd 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -106,7 +106,7 @@ impl StorageInterface for MockDb {}pub async fn get_and_deserialize_key<T>(db: &dyn StorageInterface,key: &str,- type_name: &str,+ type_name: &'static str,) -> common_utils::errors::CustomResult<T, redis_interface::errors::RedisError>whereT: serde::de::DeserializeOwned,diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rsindex 61a1a7f82d..0869fed932 100644--- a/crates/router/src/db/merchant_connector_account.rs+++ b/crates/router/src/db/merchant_connector_account.rs@@ -48,7 +48,7 @@ impl ConnectorAccessToken for Store {let access_token: Option<types::AccessToken> = maybe_token.map(|token| token.parse_struct("AccessToken")).transpose()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::UnknownError).change_context(errors::StorageError::DeserializationFailed)?;Ok(access_token)diff --git a/crates/router/src/scheduler/types/batch.rs b/crates/router/src/scheduler/types/batch.rsindex df21d4de7b..052e3953b8 100644--- a/crates/router/src/scheduler/types/batch.rs+++ b/crates/router/src/scheduler/types/batch.rs@@ -83,7 +83,7 @@ impl ProcessTrackerBatch {.as_str().parse().into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::UnknownError).change_context(errors::ProcessTrackerError::DeserializationFailed)?,).into_report()@@ -105,7 +105,7 @@ impl ProcessTrackerBatch {let trackers = serde_json::from_str::<Vec<ProcessTracker>>(trackers.as_str()).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::UnknownError).attach_printable_lazy(|| {format!("Unable to parse trackers from JSON string: {trackers:?}")})diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex 4e3615d5f6..b7ee1eb92b 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -76,7 +76,7 @@ pub fn generate_id(length: usize, prefix: &str) -> String {pub trait ConnectorResponseExt: Sized {fn get_response(self) -> RouterResult<types::Response>;fn get_error_response(self) -> RouterResult<types::Response>;- fn get_response_inner<T: DeserializeOwned>(self, type_name: &str) -> RouterResult<T> {+ fn get_response_inner<T: DeserializeOwned>(self, type_name: &'static str) -> RouterResult<T> {self.get_response()?.response.parse_struct(type_name)diff --git a/crates/router/src/utils/ext_traits.rs b/crates/router/src/utils/ext_traits.rsindex 082a499bcb..b79f4bf34b 100644--- a/crates/router/src/utils/ext_traits.rs+++ b/crates/router/src/utils/ext_traits.rs@@ -57,11 +57,11 @@ where{let value = self.get_required_value(enum_name)- .change_context(errors::ParsingError)?;+ .change_context(errors::ParsingError::UnknownError)?;E::from_str(value.as_ref()).into_report()- .change_context(errors::ParsingError)+ .change_context(errors::ParsingError::UnknownError).attach_printable_lazy(|| format!("Invalid {{ {enum_name}: {value:?} }} "))}@@ -72,7 +72,7 @@ where{let value = self.get_required_value(type_name)- .change_context(errors::ParsingError)?;+ .change_context(errors::ParsingError::UnknownError)?;value.parse_value(type_name)}