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
feat(error): add feature-gated stacktrace to error received from API (#1104)
Nishant Joshibf2352b14ae7
diff --git a/Cargo.lock b/Cargo.lockindex 100e28daaf..6cb3e12410 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1782,6 +1782,7 @@ checksum = "5f00447f331c7f726db5b8532ebc9163519eed03c6d7c8b73c90b3ff5646ac85"dependencies = ["anyhow","rustc_version",+ "serde",][[package]]diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.tomlindex c11e9cebde..7d52c2c729 100644--- a/crates/api_models/Cargo.toml+++ b/crates/api_models/Cargo.toml@@ -12,6 +12,7 @@ errors = []multiple_mca = []dummy_connector = []+detailed_errors = [][dependencies]actix-web = { version = "4.3.1", optional = true }diff --git a/crates/api_models/src/errors/types.rs b/crates/api_models/src/errors/types.rsindex d67ab17773..365be676f1 100644--- a/crates/api_models/src/errors/types.rs+++ b/crates/api_models/src/errors/types.rs@@ -15,6 +15,8 @@ pub struct ApiError {pub error_identifier: u16,pub error_message: String,pub extra: Option<Extra>,+ #[cfg(feature = "detailed_errors")]+ pub stacktrace: Option<serde_json::Value>,}impl ApiError {@@ -29,6 +31,8 @@ impl ApiError {error_identifier,error_message: error_message.to_string(),extra,+ #[cfg(feature = "detailed_errors")]+ stacktrace: None,}}}@@ -41,6 +45,9 @@ struct ErrorResponse<'a> {code: String,#[serde(flatten)]extra: &'a Option<Extra>,+ #[cfg(feature = "detailed_errors")]+ #[serde(skip_serializing_if = "Option::is_none")]+ stacktrace: Option<&'a serde_json::Value>,}impl<'a> From<&'a ApiErrorResponse> for ErrorResponse<'a> {@@ -52,6 +59,9 @@ impl<'a> From<&'a ApiErrorResponse> for ErrorResponse<'a> {message: Cow::Borrowed(value.get_internal_error().error_message.as_str()),error_type,extra: &error_info.extra,++ #[cfg(feature = "detailed_errors")]+ stacktrace: error_info.stacktrace.as_ref(),}}}@@ -114,6 +124,23 @@ impl ApiErrorResponse {}}+ pub fn get_internal_error_mut(&mut self) -> &mut ApiError {+ match self {+ Self::Unauthorized(i)+ | Self::ForbiddenCommonResource(i)+ | Self::ForbiddenPrivateResource(i)+ | Self::Conflict(i)+ | Self::Gone(i)+ | Self::Unprocessable(i)+ | Self::InternalServerError(i)+ | Self::NotImplemented(i)+ | Self::NotFound(i)+ | Self::MethodNotAllowed(i)+ | Self::BadRequest(i)+ | Self::ConnectorError(i, _) => i,+ }+ }+pub(crate) fn error_type(&self) -> &'static str {match self {Self::Unauthorized(_)diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.tomlindex 88fcf92d38..97fdd0b7fa 100644--- a/crates/router/Cargo.toml+++ b/crates/router/Cargo.toml@@ -26,6 +26,7 @@ vergen = ["router_env/vergen"]multiple_mca = ["api_models/multiple_mca"]dummy_connector = ["api_models/dummy_connector"]external_access_dc = ["dummy_connector"]+detailed_errors = ["api_models/detailed_errors", "error-stack/serde"][dependencies]diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rsindex 78c5c55171..91d95e8a8f 100644--- a/crates/router/src/compatibility/stripe/errors.rs+++ b/crates/router/src/compatibility/stripe/errors.rs@@ -609,3 +609,5 @@ impl common_utils::errors::ErrorSwitch<StripeErrorCode> for errors::ApiErrorRespself.clone().into()}}++impl crate::services::EmbedError for error_stack::Report<StripeErrorCode> {}diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rsindex 05246d3bdc..87985e71f5 100644--- a/crates/router/src/compatibility/wrap.rs+++ b/crates/router/src/compatibility/wrap.rs@@ -8,7 +8,7 @@ use serde::Serialize;use crate::{core::errors::{self, RouterResult},routes::app::AppStateInfo,- services::{api, authentication as auth, logger},+ services::{self, api, authentication as auth, logger},};#[instrument(skip(request, payload, state, func, api_authentication))]@@ -25,6 +25,7 @@ whereQ: Serialize + std::fmt::Debug + 'a,S: TryFrom<Q> + Serialize,E: Serialize + error_stack::Context + actix_web::ResponseError + Clone,+ error_stack::Report<E>: services::EmbedError,errors::ApiErrorResponse: ErrorSwitch<E>,T: std::fmt::Debug,A: AppStateInfo,diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rsindex eb06a09400..356580a520 100644--- a/crates/router/src/core/errors.rs+++ b/crates/router/src/core/errors.rs@@ -461,3 +461,47 @@ pub enum WebhooksFlowError {#[error("Dispute webhook status validation failed")]DisputeWebhookValidationFailed,}++#[cfg(feature = "detailed_errors")]+pub mod error_stack_parsing {++ #[derive(serde::Deserialize)]+ pub struct NestedErrorStack<'a> {+ context: std::borrow::Cow<'a, str>,+ attachments: Vec<std::borrow::Cow<'a, str>>,+ sources: Vec<NestedErrorStack<'a>>,+ }++ #[derive(serde::Serialize, Debug)]+ struct LinearErrorStack<'a> {+ context: std::borrow::Cow<'a, str>,+ #[serde(skip_serializing_if = "Vec::is_empty")]+ attachments: Vec<std::borrow::Cow<'a, str>>,+ }++ #[derive(serde::Serialize, Debug)]+ pub struct VecLinearErrorStack<'a>(Vec<LinearErrorStack<'a>>);++ impl<'a> From<Vec<NestedErrorStack<'a>>> for VecLinearErrorStack<'a> {+ fn from(value: Vec<NestedErrorStack<'a>>) -> Self {+ let multi_layered_errors: Vec<_> = value+ .into_iter()+ .flat_map(|current_error| {+ [LinearErrorStack {+ context: current_error.context,+ attachments: current_error.attachments,+ }]+ .into_iter()+ .chain(+ Into::<VecLinearErrorStack<'a>>::into(current_error.sources)+ .0+ .into_iter(),+ )+ })+ .collect();+ Self(multi_layered_errors)+ }+ }+}+#[cfg(feature = "detailed_errors")]+pub use error_stack_parsing::*;diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rsindex 523e55f228..3af3580baa 100644--- a/crates/router/src/core/errors/api_error_response.rs+++ b/crates/router/src/core/errors/api_error_response.rs@@ -300,6 +300,8 @@ impl actix_web::ResponseError for ApiErrorResponse {}}+impl crate::services::EmbedError for error_stack::Report<ApiErrorResponse> {}+impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse>for ApiErrorResponse{diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rsindex fb61feeedf..ca0e860284 100644--- a/crates/router/src/services/api.rs+++ b/crates/router/src/services/api.rs@@ -630,9 +630,45 @@ wherepub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponsewhereT: actix_web::ResponseError + error_stack::Context + Clone,+ Report<T>: EmbedError,{logger::error!(?error);- HttpResponse::from_error(error.current_context().clone())+ HttpResponse::from_error(error.embed().current_context().clone())+}++pub trait EmbedError: Sized {+ fn embed(self) -> Self {+ self+ }+}++impl EmbedError for Report<api_models::errors::types::ApiErrorResponse> {+ fn embed(self) -> Self {+ #[cfg(feature = "detailed_errors")]+ {+ let mut report = self;+ let error_trace = serde_json::to_value(&report).ok().and_then(|inner| {+ serde_json::from_value::<Vec<errors::NestedErrorStack<'_>>>(inner)+ .ok()+ .map(Into::<errors::VecLinearErrorStack<'_>>::into)+ .map(serde_json::to_value)+ .transpose()+ .ok()+ .flatten()+ });++ match report.downcast_mut::<api_models::errors::types::ApiErrorResponse>() {+ None => {}+ Some(inner) => {+ inner.get_internal_error_mut().stacktrace = error_trace;+ }+ }+ report+ }++ #[cfg(not(feature = "detailed_errors"))]+ self+ }}pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse {