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(core): Map tonic gRPC status codes from UCS to appropriate HTTP status codes instead of blanket 5xx (#11844)
Shubhodip pal3a6559660b51
diff --git a/Cargo.lock b/Cargo.lockindex 0d87a26b95..926427151b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4619,6 +4619,7 @@ dependencies = ["hyperswitch_domain_models","hyperswitch_masking","mime 0.3.17",+ "prost 0.14.3","reqwest 0.11.27","router_env","rust-grpc-client",@@ -4628,6 +4629,7 @@ dependencies = ["thiserror 1.0.69","time 0.3.41","tokio 1.48.0",+ "tonic 0.14.5","url 2.5.4",]diff --git a/crates/external_services/src/grpc_client/unified_connector_service.rs b/crates/external_services/src/grpc_client/unified_connector_service.rsindex ca178c0fb4..307656c3bb 100644--- a/crates/external_services/src/grpc_client/unified_connector_service.rs+++ b/crates/external_services/src/grpc_client/unified_connector_service.rs@@ -334,7 +334,12 @@ impl UnifiedConnectorServiceClient {.clone().tokenize(request).await- .change_context(UnifiedConnectorServiceError::PaymentMethodTokenizeFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -367,7 +372,12 @@ impl UnifiedConnectorServiceClient {.clone().create_client_authentication_token(request).await- .change_context(UnifiedConnectorServiceError::CreateSdkSessionTokenFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -398,7 +408,12 @@ impl UnifiedConnectorServiceClient {.clone().incremental_authorization(request).await- .change_context(UnifiedConnectorServiceError::PaymentIncrementalAuthorizationFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -428,7 +443,12 @@ impl UnifiedConnectorServiceClient {.clone().create(request).await- .change_context(UnifiedConnectorServiceError::CreateConnectorCustomerFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -459,7 +479,12 @@ impl UnifiedConnectorServiceClient {.clone().create_order(request).await- .change_context(UnifiedConnectorServiceError::PaymentCreateOrderFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -491,7 +516,12 @@ impl UnifiedConnectorServiceClient {.clone().pre_authenticate(request).await- .change_context(UnifiedConnectorServiceError::PaymentPreAuthenticateFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -523,7 +553,12 @@ impl UnifiedConnectorServiceClient {.clone().authenticate(request).await- .change_context(UnifiedConnectorServiceError::PaymentAuthenticateFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -554,7 +589,12 @@ impl UnifiedConnectorServiceClient {.clone().create_server_session_authentication_token(request).await- .change_context(UnifiedConnectorServiceError::CreateSessionTokenFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -586,7 +626,12 @@ impl UnifiedConnectorServiceClient {.clone().post_authenticate(request).await- .change_context(UnifiedConnectorServiceError::PaymentPostAuthenticateFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -618,7 +663,12 @@ impl UnifiedConnectorServiceClient {.clone().authorize(request).await- .change_context(UnifiedConnectorServiceError::PaymentAuthorizeFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -648,7 +698,12 @@ impl UnifiedConnectorServiceClient {.clone().get(request).await- .change_context(UnifiedConnectorServiceError::PaymentGetFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -678,7 +733,12 @@ impl UnifiedConnectorServiceClient {.clone().capture(request).await- .change_context(UnifiedConnectorServiceError::PaymentCaptureFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -709,7 +769,12 @@ impl UnifiedConnectorServiceClient {.clone().setup_recurring(request).await- .change_context(UnifiedConnectorServiceError::PaymentSetupRecurringFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -740,7 +805,12 @@ impl UnifiedConnectorServiceClient {.clone().charge(request).await- .change_context(UnifiedConnectorServiceError::RecurringPaymentChargeFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -770,7 +840,12 @@ impl UnifiedConnectorServiceClient {.clone().void(request).await- .change_context(UnifiedConnectorServiceError::PaymentVoidFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -800,7 +875,12 @@ impl UnifiedConnectorServiceClient {.clone().handle_event(request).await- .change_context(UnifiedConnectorServiceError::IncomingWebhookHandleEventFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -864,7 +944,12 @@ impl UnifiedConnectorServiceClient {.clone().refund(request).await- .change_context(UnifiedConnectorServiceError::PaymentRefundFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -893,7 +978,12 @@ impl UnifiedConnectorServiceClient {.clone().get(request).await- .change_context(UnifiedConnectorServiceError::RefundSyncFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -926,7 +1016,12 @@ impl UnifiedConnectorServiceClient {.clone().create(request).await- .change_context(UnifiedConnectorServiceError::PayoutCreateFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -958,7 +1053,12 @@ impl UnifiedConnectorServiceClient {.clone().create_server_authentication_token(request).await- .change_context(UnifiedConnectorServiceError::CreateAccessTokenFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -991,7 +1091,12 @@ impl UnifiedConnectorServiceClient {.clone().transfer(request).await- .change_context(UnifiedConnectorServiceError::PayoutTransferFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -1024,7 +1129,12 @@ impl UnifiedConnectorServiceClient {.clone().get(request).await- .change_context(UnifiedConnectorServiceError::PayoutGetFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -1057,7 +1167,12 @@ impl UnifiedConnectorServiceClient {.clone().void(request).await- .change_context(UnifiedConnectorServiceError::PayoutVoidFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -1090,7 +1205,12 @@ impl UnifiedConnectorServiceClient {.clone().stage(request).await- .change_context(UnifiedConnectorServiceError::PayoutStageFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -1124,7 +1244,12 @@ impl UnifiedConnectorServiceClient {.clone().create_recipient(request).await- .change_context(UnifiedConnectorServiceError::PayoutCreateRecipientFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,@@ -1158,7 +1283,12 @@ impl UnifiedConnectorServiceClient {.clone().enroll_disburse_account(request).await- .change_context(UnifiedConnectorServiceError::PayoutEnrollDisburseAccountFailure)+ .map_err(|error| {+ error_stack::Report::new(UnifiedConnectorServiceError::from_grpc_error(+ &error,+ &connector_name,+ ))+ }).inspect_err(|error| {logger::error!(grpc_error=?error,diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.tomlindex 9dc5d0ece0..8399fc4366 100644--- a/crates/hyperswitch_interfaces/Cargo.toml+++ b/crates/hyperswitch_interfaces/Cargo.toml@@ -23,12 +23,14 @@ dyn-clone = "1.0.19"error-stack = "0.4.1"http = "0.2.12"mime = "0.3.17"+prost = "0.14"reqwest = "0.11.27"serde = { version = "1.0.219", features = ["derive"] }serde_json = "1.0.140"strum = { version = "0.26", features = ["derive"] }thiserror = "1.0.69"time = "0.3.41"+tonic = "0.14"url = { version = "2.5.4", features = ["serde"] }unified-connector-service-client = { git = "https://github.com/juspay/connector-service", tag = "2026.05.25.0", package = "rust-grpc-client" }diff --git a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rsindex d2cc7c4ce3..0986dd7f82 100644--- a/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs+++ b/crates/hyperswitch_interfaces/src/unified_connector_service/transformers.rs@@ -2,9 +2,10 @@ use std::str::FromStr;use common_enums::AttemptStatus;use common_types::primitive_wrappers::{ExtendedAuthorizationAppliedBool, OvercaptureEnabledBool};-use common_utils::request::Method;+use common_utils::{errors::ErrorSwitch, request::Method};use error_stack::ResultExt;use hyperswitch_domain_models::{+ errors::api_error_response::{ApiErrorResponse, NotImplementedMessage},router_data::{AdditionalPaymentMethodConnectorResponse, ConnectorResponseData, ErrorResponse,ExtendedAuthorizationResponseData,@@ -12,12 +13,17 @@ use hyperswitch_domain_models::{router_response_types::{PaymentsResponseData, RedirectForm},};use hyperswitch_masking::ExposeInterface;+use prost::Message;use crate::{+ errors::ConnectorError,helpers::{ForeignFrom, ForeignTryFrom},unified_connector_service::payments_grpc,};+/// UCS error code indicating the connector returned a 4xx/5xx HTTP response (with `http_status_code` set).+const CONNECTOR_ERROR_RESPONSE_CODE: &str = "CONNECTOR_ERROR_RESPONSE";+/// Unified Connector Service error variants#[derive(Debug, Clone, thiserror::Error)]pub enum UnifiedConnectorServiceError {@@ -86,6 +92,21 @@ pub enum UnifiedConnectorServiceError {#[error("Failed to inject metadata into request headers: {0}")]HeaderInjectionFailed(String),+ /// Tonic gRPC status error from UCS.+ /// Use http_status() to get the corresponding HTTP status code.+ #[error("UCS error: {code:?} - {message}")]+ TonicStatus {+ /// Tonic status code+ code: tonic::Code,+ /// Error message from UCS+ message: String,+ },++ /// Connector error received through UCS (contains original connector HTTP status code).+ /// Distinguishes connector errors from UCS errors by presence of status_code.+ #[error("Connector error via UCS: {0:?}")]+ ConnectorError(Box<ConnectorErrorInner>),+/// Failed to perform Payment Create Order from gRPC Server#[error("Failed to perform Payment Create Order from gRPC Server")]PaymentCreateOrderFailure,@@ -199,6 +220,28 @@ pub enum UnifiedConnectorServiceError {PayoutEnrollDisburseAccountFailure,}+/// Inner data for [`UnifiedConnectorServiceError::ConnectorError`].+/// Boxed to keep the enum's memory footprint small.+#[derive(Debug, Clone)]+pub struct ConnectorErrorInner {+ /// Connector error code+ pub code: String,+ /// Connector error message+ pub message: String,+ /// Original HTTP status code from connector+ pub status_code: u16,+ /// Optional reason for the error+ pub reason: Option<String>,+ /// Name of the connector that returned the error+ pub connector: String,+ /// Network decline code from card scheme (e.g. Visa/Mastercard decline code)+ pub network_decline_code: Option<String>,+ /// Network advice code for retry logic+ pub network_advice_code: Option<String>,+ /// Network-specific error message+ pub network_error_message: Option<String>,+}+impl ForeignTryFrom<(payments_grpc::PaymentServiceGetResponse, AttemptStatus)>for Result<(PaymentsResponseData, AttemptStatus), ErrorResponse>{@@ -846,3 +889,232 @@ impl ForeignFrom<payments_grpc::UpiSource>}}}++impl UnifiedConnectorServiceError {+ /// Converts tonic::Code to HTTP status code.+ pub fn tonic_to_http_status(code: tonic::Code) -> u16 {+ match code {+ tonic::Code::InvalidArgument | tonic::Code::FailedPrecondition => 400,+ tonic::Code::Unauthenticated => 401,+ tonic::Code::PermissionDenied => 403,+ tonic::Code::NotFound => 404,+ tonic::Code::AlreadyExists => 409,+ tonic::Code::Unimplemented => 501,+ tonic::Code::Unavailable => 503,+ tonic::Code::DeadlineExceeded => 504,+ _ => 500,+ }+ }++ /// Returns HTTP status code for this error.+ pub fn http_status(&self) -> u16 {+ match self {+ Self::TonicStatus { code, .. } => Self::tonic_to_http_status(*code),+ Self::ConnectorError(inner) => inner.status_code,+ Self::ConnectionError(_) => 503,+ Self::InvalidDataFormat { .. }+ | Self::MissingRequiredField { .. }+ | Self::MissingRequiredFields { .. }+ | Self::RequestEncodingFailed+ | Self::RequestEncodingFailedWithReason(_)+ | Self::InvalidConnectorName+ | Self::MissingConnectorName => 400,+ Self::NotImplemented(_) => 501,+ _ => 500,+ }+ }++ /// Maps tonic::Status to UnifiedConnectorServiceError.+ /// First tries to extract a connector HTTP error from proto-encoded status details.+ pub fn from_grpc_error(status: &tonic::Status, connector_name: &str) -> Self {+ // Try to extract ConnectorError from proto-encoded status details+ if let Some(error_from_details) =+ Self::decode_connector_error_response(status, connector_name)+ {+ return error_from_details;+ }++ Self::TonicStatus {+ code: status.code(),+ message: status.message().to_string(),+ }+ }++ /// Decodes a connector HTTP error (4xx/5xx) from tonic status details, returning `None` for UCS-side errors.+ fn decode_connector_error_response(+ status: &tonic::Status,+ connector_name: &str,+ ) -> Option<Self> {+ let details = status.details();+ if details.is_empty() {+ return None;+ }++ let connector_error = payments_grpc::ConnectorError::decode(details)+ .inspect_err(|e| {+ router_env::logger::warn!(+ error = ?e,+ connector_name = connector_name,+ "Failed to decode ConnectorError from tonic status details"+ );+ })+ .ok()?;++ // Only treat as a connector HTTP error when the error code explicitly signals it.+ // Other error_code values are UCS-side errors and should fall back to TonicStatus.+ if connector_error.error_code != CONNECTOR_ERROR_RESPONSE_CODE {+ return None;+ }++ let status_code = u16::try_from(connector_error.http_status_code?).ok()?;++ Some(Self::ConnectorError(Box::new(ConnectorErrorInner {+ code: connector_error.error_code,+ message: connector_error.error_message,+ status_code,+ reason: connector_error+ .error_info+ .as_ref()+ .and_then(|ei| ei.connector_details.as_ref())+ .and_then(|cd| cd.reason.clone()),+ connector: connector_name.to_string(),+ network_decline_code: connector_error+ .error_info+ .as_ref()+ .and_then(|ei| ei.issuer_details.as_ref())+ .and_then(|id| id.network_details.as_ref())+ .and_then(|nd| nd.decline_code.clone()),+ network_advice_code: connector_error+ .error_info+ .as_ref()+ .and_then(|ei| ei.issuer_details.as_ref())+ .and_then(|id| id.network_details.as_ref())+ .and_then(|nd| nd.advice_code.clone()),+ network_error_message: connector_error+ .error_info+ .as_ref()+ .and_then(|ei| ei.issuer_details.as_ref())+ .and_then(|id| id.network_details.as_ref())+ .and_then(|nd| nd.error_message.clone()),+ })))+ }+}++impl ErrorSwitch<ApiErrorResponse> for UnifiedConnectorServiceError {+ fn switch(&self) -> ApiErrorResponse {+ match self {+ Self::TonicStatus { code, message } => match code {+ tonic::Code::InvalidArgument | tonic::Code::FailedPrecondition => {+ ApiErrorResponse::InvalidRequestData {+ message: message.clone(),+ }+ }+ tonic::Code::NotFound => ApiErrorResponse::InvalidRequestData {+ message: format!("Resource not found: {message}"),+ },+ tonic::Code::AlreadyExists => ApiErrorResponse::InvalidRequestData {+ message: format!("Resource already exists: {message}"),+ },+ tonic::Code::PermissionDenied => ApiErrorResponse::AccessForbidden {+ resource: message.clone(),+ },+ tonic::Code::Unauthenticated => ApiErrorResponse::Unauthorized,+ tonic::Code::Unimplemented => ApiErrorResponse::NotImplemented {+ message: NotImplementedMessage::Reason(message.clone()),+ },+ tonic::Code::Unavailable+ | tonic::Code::DeadlineExceeded+ | tonic::Code::Internal => ApiErrorResponse::InternalServerError,+ _ => ApiErrorResponse::InternalServerError,+ },+ Self::ConnectorError(inner) => ApiErrorResponse::ExternalConnectorError {+ code: inner.code.clone(),+ message: inner.message.clone(),+ connector: inner.connector.clone(),+ status_code: inner.status_code,+ reason: inner.reason.clone(),+ },+ _ => ApiErrorResponse::InternalServerError,+ }+ }+}++impl ErrorSwitch<ConnectorError> for UnifiedConnectorServiceError {+ fn switch(&self) -> ConnectorError {+ match self {+ // UCS validation errors (4xx from tonic) → ProcessingStepFailed with encoded error+ // body so the upstream handler can return the right HTTP status code.+ Self::TonicStatus { code, message } => {+ let status_code = Self::tonic_to_http_status(*code);+ let error_body = serde_json::json!({+ "code": format!("UCS_{}", status_code),+ "message": message,+ "status_code": status_code,+ });+ ConnectorError::ProcessingStepFailed(Some(bytes::Bytes::from(+ error_body.to_string(),+ )))+ }+ // Connector errors with status code → ResponseHandlingFailed+ Self::ConnectorError(_) => ConnectorError::ResponseHandlingFailed,+ // Connection/availability errors → ResponseHandlingFailed+ Self::ConnectionError(_) => ConnectorError::ResponseHandlingFailed,+ // Request encoding errors+ Self::RequestEncodingFailed+ | Self::RequestEncodingFailedWithReason(_)+ | Self::InvalidDataFormat { .. } => ConnectorError::RequestEncodingFailed,+ // Missing field errors+ Self::MissingRequiredField { field_name } => {+ ConnectorError::MissingRequiredField { field_name }+ }+ Self::MissingRequiredFields { field_names } => ConnectorError::MissingRequiredFields {+ field_names: field_names.clone(),+ },+ // Response deserialization errors+ Self::ResponseDeserializationFailed | Self::ParsingFailed => {+ ConnectorError::ResponseDeserializationFailed+ }+ // Auth errors+ Self::FailedToObtainAuthType => ConnectorError::FailedToObtainAuthType,+ // Not implemented+ Self::NotImplemented(msg) => ConnectorError::NotImplemented(msg.clone()),+ // Invalid connector name+ Self::InvalidConnectorName | Self::MissingConnectorName => {+ ConnectorError::InvalidConnectorName+ }+ // Header injection errors → request encoding failure+ Self::HeaderInjectionFailed(_) => ConnectorError::RequestEncodingFailed,+ // Webhook processing errors+ Self::WebhookProcessingFailure => ConnectorError::ResponseHandlingFailed,+ // All other gRPC operation failures+ Self::PaymentCreateOrderFailure+ | Self::PaymentAuthorizeGranularFailure+ | Self::CreateSessionTokenFailure+ | Self::CreateAccessTokenFailure+ | Self::PaymentMethodTokenizeFailure+ | Self::CreateConnectorCustomerFailure+ | Self::PaymentAuthorizeFailure+ | Self::PaymentPreAuthenticateFailure+ | Self::PaymentAuthenticateFailure+ | Self::PaymentPostAuthenticateFailure+ | Self::PaymentGetFailure+ | Self::PaymentCaptureFailure+ | Self::PaymentSetupRecurringFailure+ | Self::RecurringPaymentChargeFailure+ | Self::PaymentRefundFailure+ | Self::RefundSyncFailure+ | Self::IncomingWebhookHandleEventFailure+ | Self::IncomingWebhookParseEventFailure+ | Self::PaymentVoidFailure+ | Self::CreateSdkSessionTokenFailure+ | Self::PaymentIncrementalAuthorizationFailure+ | Self::PayoutCreateFailure+ | Self::PayoutTransferFailure+ | Self::PayoutGetFailure+ | Self::PayoutVoidFailure+ | Self::PayoutStageFailure+ | Self::PayoutCreateRecipientFailure+ | Self::PayoutEnrollDisburseAccountFailure => ConnectorError::ResponseHandlingFailed,+ }+ }+}diff --git a/crates/router/src/core/payments/gateway.rs b/crates/router/src/core/payments/gateway.rsindex 5b4d054eac..7cdf512ba0 100644--- a/crates/router/src/core/payments/gateway.rs+++ b/crates/router/src/core/payments/gateway.rs@@ -20,10 +20,14 @@ pub mod setup_mandate;use std::sync;use common_enums;+use common_utils::errors::ErrorSwitch;+use error_stack::Report;use hyperswitch_domain_models::{router_data_v2::PaymentFlowData, router_flow_types::payments};use hyperswitch_interfaces::{api::{gateway, Connector, ConnectorIntegration},connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2},+ errors::ConnectorError,+ unified_connector_service::transformers::UnifiedConnectorServiceError,};use crate::{@@ -87,3 +91,14 @@ where.to_payment_failed_response()?;Ok(resp)}++/// Converts a `Report<UnifiedConnectorServiceError>` into a `Report<ConnectorError>`+/// using the `ErrorSwitch` trait for consistent, exhaustive mapping.+///+/// Shared by all payment gateway files (authorize, psync, capture, void) to avoid duplication.+pub(crate) fn convert_ucs_error_to_connector_error(+ report: Report<UnifiedConnectorServiceError>,+) -> Report<ConnectorError> {+ let connector_error = report.current_context().switch();+ report.change_context(connector_error)+}diff --git a/crates/router/src/core/payments/gateway/authorize_gateway.rs b/crates/router/src/core/payments/gateway/authorize_gateway.rsindex dc9b137e10..bf3bb75799 100644--- a/crates/router/src/core/payments/gateway/authorize_gateway.rs+++ b/crates/router/src/core/payments/gateway/authorize_gateway.rs@@ -9,6 +9,7 @@ use hyperswitch_interfaces::{api::gateway as payment_gateway,connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},errors::ConnectorError,+ unified_connector_service::transformers::UnifiedConnectorServiceError,};use hyperswitch_masking::ExposeInterface as UcsMaskingExposeInterface;use unified_connector_service_client::payments as payments_grpc;@@ -132,13 +133,58 @@ wheregrpc_headers,unified_connector_service_execution_mode,|mut router_data, recurring_payment_charge_request, grpc_headers| async move {- let response = Box::pin(client.recurring_payment_charge(+ let response = match Box::pin(client.recurring_payment_charge(recurring_payment_charge_request,connector_auth_metadata,grpc_headers,)).await- .attach_printable("Failed to charge recurring payment")?;+ {+ Ok(resp) => resp,+ Err(report) => {+ // Check if this is a connector error (4xx/5xx from connector via UCS)+ if let UnifiedConnectorServiceError::ConnectorError(inner) =+ report.current_context()+ {+ let (code, message, status_code, reason,+ network_decline_code, network_advice_code,+ network_error_message, connector) = (+ &inner.code, &inner.message, inner.status_code,+ &inner.reason, &inner.network_decline_code,+ &inner.network_advice_code, &inner.network_error_message,+ &inner.connector,+ );+ logger::info!(+ "Connector error via UCS for recurring charge (connector {}, status {}): {} - {}",+ connector,+ status_code,+ code,+ message+ );+ router_data.response =+ Err(hyperswitch_domain_models::router_data::ErrorResponse {+ code: code.clone(),+ message: message.clone(),+ reason: reason.clone(),+ status_code,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_decline_code: network_decline_code.clone(),+ network_advice_code: network_advice_code.clone(),+ network_error_message: network_error_message.clone(),+ connector_metadata: None,+ });+ return Ok((+ router_data,+ (),+ payments_grpc::RecurringPaymentServiceChargeResponse::default(),+ ));+ }+ // Propagate as Err for proper HTTP error handling+ return Err(report.attach_printable("Failed to charge recurring payment"));+ }+ };let recurring_payment_charge_response = response.into_inner();@@ -187,7 +233,7 @@ where)).await.map(|(router_data, _)| router_data)- .change_context(ConnectorError::ResponseHandlingFailed)?+ .map_err(super::convert_ucs_error_to_connector_error)?} else {logger::debug!("Granular Gateway: Regular authorize flow");let granular_authorize_request =@@ -205,13 +251,73 @@ wheregrpc_headers,unified_connector_service_execution_mode,|mut router_data, granular_authorize_request, grpc_headers| async move {- let response = Box::pin(client.payment_authorize(+ let response = match Box::pin(client.payment_authorize(granular_authorize_request,connector_auth_metadata,grpc_headers,)).await- .attach_printable("Failed to authorize payment")?;+ {+ Ok(resp) => resp,+ Err(report) => {+ // Check if this is a connector error (4xx/5xx from connector via UCS)+ // If so, set it as router_data.response = Err(ErrorResponse) and return Ok+ // This matches how direct connector errors are handled+ if let UnifiedConnectorServiceError::ConnectorError(inner) =+ report.current_context()+ {+ let (+ code,+ message,+ status_code,+ reason,+ network_decline_code,+ network_advice_code,+ network_error_message,+ connector,+ ) = (+ &inner.code,+ &inner.message,+ inner.status_code,+ &inner.reason,+ &inner.network_decline_code,+ &inner.network_advice_code,+ &inner.network_error_message,+ &inner.connector,+ );+ logger::info!(+ "Connector error via UCS (connector {}, status {}): {} - {}",+ connector,+ status_code,+ code,+ message+ );+ router_data.response =+ Err(hyperswitch_domain_models::router_data::ErrorResponse {+ code: code.clone(),+ message: message.clone(),+ reason: reason.clone(),+ status_code,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_decline_code: network_decline_code.clone(),+ network_advice_code: network_advice_code.clone(),+ network_error_message: network_error_message.clone(),+ connector_metadata: None,+ });+ // Return Ok with router_data containing the error response+ // This ensures the connector error flows through the normal+ // response handling path (same as direct connector errors)+ return Ok((+ router_data,+ (),+ payments_grpc::PaymentServiceAuthorizeResponse::default(),+ ));+ }+ return Err(report.attach_printable("Failed to authorize payment"));+ }+ };let payment_authorize_response = response.into_inner();@@ -258,7 +364,7 @@ where)).await.map(|(router_data, _)| router_data)- .change_context(ConnectorError::ResponseHandlingFailed)?+ .map_err(super::convert_ucs_error_to_connector_error)?};Ok(updated_router_data)diff --git a/crates/router/src/core/payments/gateway/cancel_gateway.rs b/crates/router/src/core/payments/gateway/cancel_gateway.rsindex bd3cfa6674..6180cad8f3 100644--- a/crates/router/src/core/payments/gateway/cancel_gateway.rs+++ b/crates/router/src/core/payments/gateway/cancel_gateway.rs@@ -9,6 +9,7 @@ use hyperswitch_interfaces::{api::gateway as payment_gateway,connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},errors::ConnectorError,+ unified_connector_service::transformers::UnifiedConnectorServiceError,};use unified_connector_service_client::payments as payments_grpc;@@ -114,10 +115,53 @@ whereheader_payload,unified_connector_service_execution_mode,|mut router_data, payment_void_request, grpc_headers| async move {- let response = client+ let response = match client.payment_void(payment_void_request, connector_auth_metadata, grpc_headers).await- .attach_printable("Failed to Void payment")?;+ {+ Ok(resp) => resp,+ Err(report) => {+ if let UnifiedConnectorServiceError::ConnectorError(inner) =+ report.current_context()+ {+ let (code, message, status_code, reason,+ network_decline_code, network_advice_code, network_error_message,+ connector) = (+ &inner.code, &inner.message, inner.status_code, &inner.reason,+ &inner.network_decline_code, &inner.network_advice_code,+ &inner.network_error_message, &inner.connector,+ );+ logger::info!(+ "Connector error via UCS for void (connector {}, status {}): {} - {}",+ connector,+ status_code,+ code,+ message+ );+ router_data.response = Err(+ hyperswitch_domain_models::router_data::ErrorResponse {+ code: code.clone(),+ message: message.clone(),+ reason: reason.clone(),+ status_code,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_decline_code: network_decline_code.clone(),+ network_advice_code: network_advice_code.clone(),+ network_error_message: network_error_message.clone(),+ connector_metadata: None,+ },+ );+ return Ok((+ router_data,+ (),+ payments_grpc::PaymentServiceVoidResponse::default(),+ ));+ }+ return Err(report.attach_printable("Failed to Void payment"));+ }+ };let payment_void_response = response.into_inner();@@ -149,7 +193,7 @@ where)).await.map(|(router_data, _)| router_data)- .change_context(ConnectorError::ResponseHandlingFailed)+ .map_err(super::convert_ucs_error_to_connector_error)}}diff --git a/crates/router/src/core/payments/gateway/capture_gateway.rs b/crates/router/src/core/payments/gateway/capture_gateway.rsindex fa65ca4cb8..bb862e51dc 100644--- a/crates/router/src/core/payments/gateway/capture_gateway.rs+++ b/crates/router/src/core/payments/gateway/capture_gateway.rs@@ -9,6 +9,7 @@ use hyperswitch_interfaces::{api::gateway as payment_gateway,connector_integration_interface::{BoxedConnectorIntegrationInterface, RouterDataConversion},errors::ConnectorError,+ unified_connector_service::transformers::UnifiedConnectorServiceError,};use unified_connector_service_client::payments as payments_grpc;@@ -112,14 +113,57 @@ whereheader_payload,unified_connector_service_execution_mode,|mut router_data, payment_capture_request, grpc_headers| async move {- let response = client+ let response = match client.payment_capture(payment_capture_request,connector_auth_metadata,grpc_headers,).await- .attach_printable("Failed to capture payment")?;+ {+ Ok(resp) => resp,+ Err(report) => {+ if let UnifiedConnectorServiceError::ConnectorError(inner) =+ report.current_context()+ {+ let (code, message, status_code, reason,+ network_decline_code, network_advice_code, network_error_message,+ connector) = (+ &inner.code, &inner.message, inner.status_code, &inner.reason,+ &inner.network_decline_code, &inner.network_advice_code,+ &inner.network_error_message, &inner.connector,+ );+ logger::info!(+ "Connector error via UCS for capture (connector {}, status {}): {} - {}",+ connector,+ status_code,+ code,+ message+ );+ router_data.response = Err(+ hyperswitch_domain_models::router_data::ErrorResponse {+ code: code.clone(),+ message: message.clone(),+ reason: reason.clone(),+ status_code,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_decline_code: network_decline_code.clone(),+ network_advice_code: network_advice_code.clone(),+ network_error_message: network_error_message.clone(),+ connector_metadata: None,+ },+ );+ return Ok((+ router_data,+ (),+ payments_grpc::PaymentServiceCaptureResponse::default(),+ ));+ }+ return Err(report.attach_printable("Failed to capture payment"));+ }+ };let payment_capture_response = response.into_inner();@@ -155,7 +199,7 @@ where)).await.map(|(router_data, _)| router_data)- .change_context(ConnectorError::ResponseHandlingFailed)+ .map_err(super::convert_ucs_error_to_connector_error)}}diff --git a/crates/router/src/core/payments/gateway/psync_gateway.rs b/crates/router/src/core/payments/gateway/psync_gateway.rsindex cfcc2574e2..35e9f0488e 100644--- a/crates/router/src/core/payments/gateway/psync_gateway.rs+++ b/crates/router/src/core/payments/gateway/psync_gateway.rs@@ -12,6 +12,7 @@ use hyperswitch_interfaces::{unified_connector_service::{get_payments_response_from_ucs_webhook_content,handle_unified_connector_service_response_for_payment_get,+ transformers::UnifiedConnectorServiceError,},};use hyperswitch_masking::ExposeInterface as UcsMaskingExposeInterface;@@ -193,10 +194,54 @@ whereheader_payload,unified_connector_service_execution_mode,|mut router_data, payment_get_request, grpc_headers| async move {- let response = client+ let response = match client.payment_get(payment_get_request, connector_auth_metadata, grpc_headers).await- .attach_printable("Failed to get payment")?;+ {+ Ok(resp) => resp,+ Err(report) => {+ if let UnifiedConnectorServiceError::ConnectorError(inner) =+ report.current_context()+ {+ let (code, message, status_code, reason,+ network_decline_code, network_advice_code,+ network_error_message, connector) = (+ &inner.code, &inner.message, inner.status_code,+ &inner.reason, &inner.network_decline_code,+ &inner.network_advice_code, &inner.network_error_message,+ &inner.connector,+ );+ logger::info!(+ "Connector error via UCS for psync (connector {}, status {}): {} - {}",+ connector,+ status_code,+ code,+ message+ );+ router_data.response = Err(+ hyperswitch_domain_models::router_data::ErrorResponse {+ code: code.clone(),+ message: message.clone(),+ reason: reason.clone(),+ status_code,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_decline_code: network_decline_code.clone(),+ network_advice_code: network_advice_code.clone(),+ network_error_message: network_error_message.clone(),+ connector_metadata: None,+ },+ );+ return Ok((+ router_data,+ (),+ payments_grpc::PaymentServiceGetResponse::default(),+ ));+ }+ return Err(report.attach_printable("Failed to get payment"));+ }+ };let payment_get_response = response.into_inner();@@ -243,7 +288,7 @@ where)).await.map(|(router_data, _)| router_data)- .change_context(ConnectorError::ResponseHandlingFailed)+ .map_err(super::convert_ucs_error_to_connector_error)}_ => Err(ConnectorError::ResponseHandlingFailed).attach_printable("Invalid CallConnectorAction for payment sync via UCS Gateway system",diff --git a/crates/router/src/core/unified_connector_service.rs b/crates/router/src/core/unified_connector_service.rsindex 1de6c036a5..716dab5839 100644--- a/crates/router/src/core/unified_connector_service.rs+++ b/crates/router/src/core/unified_connector_service.rs@@ -1,5 +1,6 @@use std::{borrow::Cow, str::FromStr, time::Instant};+use actix_web::ResponseError;use api_models::admin;#[cfg(feature = "v2")]use base64::Engine;@@ -10,7 +11,11 @@ use common_enums::{#[cfg(feature = "v2")]use common_utils::consts::BASE64_ENGINE;use common_utils::{- errors::CustomResult, ext_traits::ValueExt, id_type, request::Method, ucs_types,+ errors::{CustomResult, ErrorSwitch},+ ext_traits::ValueExt,+ id_type,+ request::Method,+ ucs_types,};use diesel_models::types::FeatureMetadata;use error_stack::ResultExt;@@ -64,6 +69,7 @@ use crate::{pub mod connector_config;pub mod transformers;+/// Returns Apple Pay data from payment method token when it has decrypt data,/// otherwise returns the original payment data.fn get_apple_pay_payment_data(@@ -2589,7 +2595,11 @@ where"error": error.to_string(),"error_type": "ucs_call_failed"});- (500, Some(error_body), Err(error))+ (+ error.current_context().status_code().as_u16(),+ Some(error_body),+ Err(error),+ )}};@@ -2733,7 +2743,11 @@ where"error": error.to_string(),"error_type": "ucs_call_failed"});- (500, Some(error_body), Err(error))+ (+ error.current_context().http_status(),+ Some(error_body),+ Err(error),+ )}};@@ -2921,13 +2935,51 @@ pub async fn call_unified_connector_service_for_refund_execute(ucs_refund_request,grpc_header_builder,execution_mode,- |router_data, grpc_request, grpc_headers| async move {+ |mut router_data, grpc_request, grpc_headers| async move {// Call UCS payment_refund method- let response = ucs_client+ let response = match ucs_client.payment_refund(grpc_request, connector_auth_metadata, grpc_headers).await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("UCS refund execution failed")?;+ {+ Ok(resp) => resp,+ Err(report) => {+ if let UnifiedConnectorServiceError::ConnectorError(inner) =+ report.current_context()+ {+ let (code, message, status_code, reason, connector,+ network_decline_code, network_advice_code, network_error_message) = (+ &inner.code, &inner.message, inner.status_code, &inner.reason,+ &inner.connector, &inner.network_decline_code,+ &inner.network_advice_code, &inner.network_error_message,+ );+ logger::info!(+ "Connector error via UCS for refund execute (connector {}, status {}): {} - {}",+ connector,+ status_code,+ code,+ message+ );+ router_data.response = Err(ErrorResponse {+ code: code.clone(),+ message: message.clone(),+ reason: reason.clone(),+ status_code,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_decline_code: network_decline_code.clone(),+ network_advice_code: network_advice_code.clone(),+ network_error_message: network_error_message.clone(),+ connector_metadata: None,+ });+ return Ok((router_data, (), payments_grpc::RefundResponse::default()));+ }+ let api_error = report.current_context().switch();+ return Err(report+ .change_context(api_error)+ .attach_printable("UCS refund execution failed"));+ }+ };let grpc_response = response.into_inner();@@ -2937,11 +2989,10 @@ pub async fn call_unified_connector_service_for_refund_execute(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to transform UCS refund response")?;- let mut updated_router_data = router_data;- updated_router_data.response = refund_response_data;- updated_router_data.connector_http_status_code = Some(status_code);+ router_data.response = refund_response_data;+ router_data.connector_http_status_code = Some(status_code);- Ok((updated_router_data, (), grpc_response))+ Ok((router_data, (), grpc_response))},)).await@@ -3014,13 +3065,51 @@ pub async fn call_unified_connector_service_for_refund_sync(ucs_refund_sync_request,grpc_header_builder,execution_mode,- |router_data, grpc_request, grpc_headers| async move {+ |mut router_data, grpc_request, grpc_headers| async move {// Call UCS refund_sync method- let response = ucs_client+ let response = match ucs_client.refund_get(grpc_request, connector_auth_metadata, grpc_headers).await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("UCS refund sync execution failed")?;+ {+ Ok(resp) => resp,+ Err(report) => {+ if let UnifiedConnectorServiceError::ConnectorError(inner) =+ report.current_context()+ {+ let (code, message, status_code, reason, connector,+ network_decline_code, network_advice_code, network_error_message) = (+ &inner.code, &inner.message, inner.status_code, &inner.reason,+ &inner.connector, &inner.network_decline_code,+ &inner.network_advice_code, &inner.network_error_message,+ );+ logger::info!(+ "Connector error via UCS for refund sync (connector {}, status {}): {} - {}",+ connector,+ status_code,+ code,+ message+ );+ router_data.response = Err(ErrorResponse {+ code: code.clone(),+ message: message.clone(),+ reason: reason.clone(),+ status_code,+ attempt_status: None,+ connector_transaction_id: None,+ connector_response_reference_id: None,+ network_decline_code: network_decline_code.clone(),+ network_advice_code: network_advice_code.clone(),+ network_error_message: network_error_message.clone(),+ connector_metadata: None,+ });+ return Ok((router_data, (), payments_grpc::RefundResponse::default()));+ }+ let api_error = report.current_context().switch();+ return Err(report+ .change_context(api_error)+ .attach_printable("UCS refund sync execution failed"));+ }+ };let grpc_response = response.into_inner();@@ -3030,11 +3119,10 @@ pub async fn call_unified_connector_service_for_refund_sync(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to transform UCS refund get response")?;- let mut updated_router_data = router_data;- updated_router_data.response = refund_response_data;- updated_router_data.connector_http_status_code = Some(status_code);+ router_data.response = refund_response_data;+ router_data.connector_http_status_code = Some(status_code);- Ok((updated_router_data, (), grpc_response))+ Ok((router_data, (), grpc_response))},)).await