From 0ea5ec3357ae44651ffdab0eb669a566c6fbce7f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Dzivjak?= Date: Mon, 26 Oct 2026 09:20:29 +0100 Subject: [PATCH 1/3] feat!: preserve API error responses and expose Problem details Expose typed Problem details and preserve error response context. Add focused regression coverage and concise integration examples. BREAKING CHANGE: API error variants now contain boxed ApiErrorResponse values. Read the payload through response.body when matching variants. --- README.md | 18 ++ codegen/src/operation.rs | 47 ++-- sdk/src/error.rs | 130 +++++++++-- sdk/src/events_handler.rs | 8 +- sdk/src/lib.rs | 8 +- sdk/src/resources/checkouts.rs | 259 ++++++++++++---------- sdk/src/resources/customers.rs | 208 ++++++++++-------- sdk/src/resources/members.rs | 147 ++++++++----- sdk/src/resources/memberships.rs | 28 ++- sdk/src/resources/merchants.rs | 61 +++--- sdk/src/resources/payouts.rs | 31 +-- sdk/src/resources/readers.rs | 343 ++++++++++++++++++------------ sdk/src/resources/receipts.rs | 34 +-- sdk/src/resources/roles.rs | 122 +++++++---- sdk/src/resources/transactions.rs | 109 ++++++---- sdk/tests/api_errors.rs | 64 ++++++ 16 files changed, 1027 insertions(+), 590 deletions(-) create mode 100644 sdk/tests/api_errors.rs diff --git a/README.md b/README.md index 734e3f6..7e815d6 100644 --- a/README.md +++ b/README.md @@ -138,3 +138,21 @@ Published releases synchronize this catalog to `sumup/sumup-developer` as `src/codesamples/rust.json`. [docs-badge]: https://img.shields.io/badge/SumUp-documentation-white.svg?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgY29sb3I9IndoaXRlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogICAgPHBhdGggZD0iTTIyLjI5IDBIMS43Qy43NyAwIDAgLjc3IDAgMS43MVYyMi4zYzAgLjkzLjc3IDEuNyAxLjcxIDEuN0gyMi4zYy45NCAwIDEuNzEtLjc3IDEuNzEtMS43MVYxLjdDMjQgLjc3IDIzLjIzIDAgMjIuMjkgMFptLTcuMjIgMTguMDdhNS42MiA1LjYyIDAgMCAxLTcuNjguMjQuMzYuMzYgMCAwIDEtLjAxLS40OWw3LjQ0LTcuNDRhLjM1LjM1IDAgMCAxIC40OSAwIDUuNiA1LjYgMCAwIDEtLjI0IDcuNjlabTEuNTUtMTEuOS03LjQ0IDcuNDVhLjM1LjM1IDAgMCAxLS41IDAgNS42MSA1LjYxIDAgMCAxIDcuOS03Ljk2bC4wMy4wM2MuMTMuMTMuMTQuMzUuMDEuNDlaIiBmaWxsPSJjdXJyZW50Q29sb3IiLz4KPC9zdmc+ + +## Handling errors + +API errors retain their HTTP status, headers, and original response bytes. Read typed +Problem details directly when available: + +```rust +if let Err(error) = client.checkouts().get("your-checkout-id").await { + if let Some(problem) = error.problem() { + println!("{}: {:?}", problem.r#type, problem.detail); + } + println!("{:?}", error.status()); +} +``` + +Use `body()` for the endpoint's typed error enum, `headers()` for response headers, +and `raw_body()` for the original bytes. When matching `SdkError::Api(response)`, +the typed body is in `response.body`. diff --git a/codegen/src/operation.rs b/codegen/src/operation.rs index 581e928..7d08e07 100644 --- a/codegen/src/operation.rs +++ b/codegen/src/operation.rs @@ -709,6 +709,7 @@ fn generate_error_handling( let enum_ident = Ident::new(&enum_name, Span::call_site()); let mut variant_defs = Vec::new(); + let mut problem_arms = Vec::new(); let mut seen_variants: Vec = Vec::new(); let mut match_arms = Vec::new(); @@ -722,6 +723,10 @@ fn generate_error_handling( match &body_kind { BodyKind::Schema(ident) => { variant_defs.push(quote! { #variant_ident(#ident), }); + if ident == "Problem" { + problem_arms + .push(quote! { Self::#variant_ident(problem) => Some(problem), }); + } } BodyKind::Unknown => { variant_defs.push(quote! { #variant_ident(crate::error::UnknownApiBody), }); @@ -737,35 +742,49 @@ fn generate_error_handling( BodyKind::Schema(ident) => { match_arms.push(quote! { #status_const => { - let body: #ident = response.json().await?; - Err(crate::error::SdkError::api(#enum_ident::#variant_ident(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::<#ident>(raw).map(#enum_ident::#variant_ident) + }).await) } }); } BodyKind::Unknown => { match_arms.push(quote! { #status_const => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::api(#enum_ident::#variant_ident(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + Ok(#enum_ident::#variant_ident(crate::error::UnknownApiBody::from_bytes(raw))) + }).await) } }); } BodyKind::Empty => { match_arms.push(quote! { #status_const => { - Err(crate::error::SdkError::api(#enum_ident::#variant_ident)) + Err(crate::error::SdkError::from_response(response, |_| Ok(#enum_ident::#variant_ident)).await) } }); } } } + let problem_body = if problem_arms.is_empty() { + quote! { None } + } else if problem_arms.len() == variant_defs.len() { + quote! { match self { #(#problem_arms)* } } + } else { + quote! { match self { #(#problem_arms)* _ => None } } + }; + let body_definition = Some(quote! { #[derive(Debug, PartialEq)] pub enum #enum_ident { #(#variant_defs)* } + impl crate::error::ProblemDetails for #enum_ident { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + #problem_body + } + } }); Ok(ErrorGeneration { @@ -866,9 +885,7 @@ fn generate_no_success_response_handling( match status { #(#error_arms)* _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::unexpected_response(response).await) } } } @@ -907,9 +924,7 @@ fn generate_single_response_handling( } #(#error_arms)* _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::unexpected_response(response).await) } } }) @@ -920,9 +935,7 @@ fn generate_single_response_handling( #status_const => Ok(()), #(#error_arms)* _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::unexpected_response(response).await) } } }) @@ -1023,9 +1036,7 @@ fn generate_multi_response_handling( #(#match_arms)* #(#error_arms)* _ => { - let body = response.text().await?; - let body = crate::error::UnknownApiBody::from_text(body); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::unexpected_response(response).await) } } }) diff --git a/sdk/src/error.rs b/sdk/src/error.rs index f86f36c..535f4c8 100644 --- a/sdk/src/error.rs +++ b/sdk/src/error.rs @@ -12,9 +12,9 @@ pub enum SdkError { /// Errors originating from the underlying HTTP client (network, TLS, etc.). Network(reqwest::Error), /// The server returned an API response with an expected error payload. - Api(E), + Api(Box>), /// The server returned an unexpected status or payload. - Unexpected(reqwest::StatusCode, UnknownApiBody), + Unexpected(Box>), } impl SdkError { @@ -23,29 +23,64 @@ impl SdkError { Self::Network(error) } - /// Creates a new API error using the supplied body payload. - pub fn api(body: E) -> Self { - Self::Api(body) + /// Reads an API error while retaining its HTTP response context. + #[doc(hidden)] + pub async fn from_response( + response: reqwest::Response, + decode: impl FnOnce(&[u8]) -> Result, + ) -> Self { + let status = response.status(); + let headers = response.headers().clone(); + let raw_body = match response.bytes().await { + Ok(bytes) => bytes.to_vec(), + Err(error) => return Self::Network(error), + }; + match decode(&raw_body) { + Ok(body) => Self::Api(Box::new(ApiErrorResponse { + status, + headers, + body, + raw_body, + })), + Err(_) => Self::Unexpected(Box::new(ApiErrorResponse { + status, + headers, + body: UnknownApiBody::from_bytes(&raw_body), + raw_body, + })), + } } - /// Creates an unexpected API error preserving the raw payload. - pub fn unexpected(status: reqwest::StatusCode, body: UnknownApiBody) -> Self { - Self::Unexpected(status, body) + /// Reads an unrecognized API response without losing its status or payload. + #[doc(hidden)] + pub async fn unexpected_response(response: reqwest::Response) -> Self { + let status = response.status(); + let headers = response.headers().clone(); + match response.bytes().await { + Ok(bytes) => Self::Unexpected(Box::new(ApiErrorResponse { + status, + headers, + body: UnknownApiBody::from_bytes(&bytes), + raw_body: bytes.to_vec(), + })), + Err(error) => Self::Network(error), + } } /// Returns the HTTP status code associated with this error when available. pub fn status(&self) -> Option { match self { Self::Network(err) => err.status(), - Self::Unexpected(status, _) => Some(*status), - Self::Api(_) | Self::InvalidRequest(_) => None, + Self::Unexpected(response) => Some(response.status), + Self::Api(response) => Some(response.status), + Self::InvalidRequest(_) => None, } } /// Returns the captured error body when the server responded with an expected error payload. pub fn body(&self) -> Option<&E> { match self { - Self::Api(body) => Some(body), + Self::Api(response) => Some(&response.body), _ => None, } } @@ -53,7 +88,7 @@ impl SdkError { /// Returns the captured unexpected body, when available. pub fn unexpected_body(&self) -> Option<&UnknownApiBody> { match self { - Self::Unexpected(_, body) => Some(body), + Self::Unexpected(response) => Some(&response.body), _ => None, } } @@ -61,7 +96,24 @@ impl SdkError { /// Consumes the error, yielding the captured API body when available. pub fn into_body(self) -> Option { match self { - Self::Api(body) => Some(body), + Self::Api(response) => Some(response.body), + _ => None, + } + } + /// Returns the response headers for an API failure. + pub fn headers(&self) -> Option<&reqwest::header::HeaderMap> { + match self { + Self::Api(response) => Some(&response.headers), + Self::Unexpected(response) => Some(&response.headers), + _ => None, + } + } + + /// Returns the original response bytes for an API failure. + pub fn raw_body(&self) -> Option<&[u8]> { + match self { + Self::Api(response) => Some(&response.raw_body), + Self::Unexpected(response) => Some(&response.raw_body), _ => None, } } @@ -81,9 +133,15 @@ where match self { Self::InvalidRequest(reason) => write!(f, "invalid request: {reason}"), Self::Network(err) => write!(f, "network error: {}", err), - Self::Api(body) => write!(f, "API error: {:?}", body), - Self::Unexpected(status, body) => { - write!(f, "unexpected API error ({}): {}", status, body) + Self::Api(response) => { + write!(f, "API error ({}): {:?}", response.status, response.body) + } + Self::Unexpected(response) => { + write!( + f, + "unexpected API error ({}): {}", + response.status, response.body + ) } } } @@ -101,10 +159,37 @@ where } } +/// An API response with typed error details and its original HTTP context. +#[derive(Debug)] +pub struct ApiErrorResponse { + pub status: reqwest::StatusCode, + pub headers: reqwest::header::HeaderMap, + pub body: E, + pub raw_body: Vec, +} + +/// Provides typed Problem details for generated error bodies. +pub trait ProblemDetails { + fn problem(&self) -> Option<&crate::resources::common::Problem>; +} + +impl SdkError { + /// Returns typed Problem details when this API failure contains them. + pub fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Api(response) => response.body.problem(), + Self::Unexpected(response) => response.body.problem(), + _ => None, + } + } +} + /// Describes an unexpected SumUp API error payload. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(untagged)] pub enum UnknownApiBody { + /// A Problem response received outside the documented error cases. + Problem(crate::resources::common::Problem), /// JSON payload when the body was valid JSON but schema is unknown. Json(serde_json::Value), /// Plain text fallback. @@ -120,6 +205,9 @@ impl UnknownApiBody { return Self::Empty; } + if let Ok(problem) = serde_json::from_slice::(bytes) { + return Self::Problem(problem); + } if let Ok(json) = serde_json::from_slice(bytes) { Self::Json(json) } else if let Ok(text) = std::str::from_utf8(bytes) { @@ -135,9 +223,19 @@ impl UnknownApiBody { } } +impl ProblemDetails for UnknownApiBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Problem(problem) => Some(problem), + _ => None, + } + } +} + impl std::fmt::Display for UnknownApiBody { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { + Self::Problem(problem) => write!(f, "{}", problem), Self::Json(value) => write!(f, "{}", value), Self::Text(text) => write!(f, "{}", text), Self::Empty => write!(f, ""), diff --git a/sdk/src/events_handler.rs b/sdk/src/events_handler.rs index 1ec40f3..6ead48f 100644 --- a/sdk/src/events_handler.rs +++ b/sdk/src/events_handler.rs @@ -343,11 +343,7 @@ where let status = response.status(); match status { reqwest::StatusCode::OK => response.json().await.map_err(Into::into), - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) - } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } @@ -1032,7 +1028,7 @@ mod tests { .await .expect_err("return SDK error"); - assert!(matches!(error, crate::error::SdkError::Unexpected(_, _))); + assert!(matches!(error, crate::error::SdkError::Unexpected(_))); assert_eq!(error.status(), Some(reqwest::StatusCode::NOT_FOUND)); assert_eq!( error.unexpected_body(), diff --git a/sdk/src/lib.rs b/sdk/src/lib.rs index 27cab4a..22be591 100644 --- a/sdk/src/lib.rs +++ b/sdk/src/lib.rs @@ -144,11 +144,11 @@ //! let client = Client::default(); //! match client.checkouts().list(Default::default()).await { //! Ok(checkouts) => println!("retrieved {} checkouts", checkouts.len()), -//! Err(SdkError::Api(body)) => match body { +//! Err(SdkError::Api(response)) => match response.body { //! ListErrorBody::Unauthorized(details) => eprintln!("unauthorized: {:?}", details), //! }, -//! Err(SdkError::Unexpected(status, body)) => { -//! eprintln!("unexpected {} response: {}", status, body); +//! Err(SdkError::Unexpected(response)) => { +//! eprintln!("unexpected {} response: {}", response.status, response.body); //! } //! Err(SdkError::Network(err)) => panic!("network error: {}", err), //! Err(SdkError::InvalidRequest(reason)) => eprintln!("invalid request: {}", reason), @@ -194,7 +194,7 @@ pub mod resources; pub use crate::resources::*; pub use auth::Authorization; pub use client::Client; -pub use error::{SdkError, SdkResult, UnknownApiBody}; +pub use error::{ApiErrorResponse, ProblemDetails, SdkError, SdkResult, UnknownApiBody}; pub use nullable::Nullable; pub use secret::Secret; pub use version::VERSION; diff --git a/sdk/src/resources/checkouts.rs b/sdk/src/resources/checkouts.rs index cc9bd07..37c0cdd 100644 --- a/sdk/src/resources/checkouts.rs +++ b/sdk/src/resources/checkouts.rs @@ -1212,6 +1212,13 @@ use crate::client::Client; pub enum ListErrorBody { Unauthorized(Problem), } +impl crate::error::ProblemDetails for ListErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum CreateErrorBody { BadRequest(ErrorExtended), @@ -1219,22 +1226,54 @@ pub enum CreateErrorBody { Forbidden(ErrorForbidden), Conflict(Error), } +impl crate::error::ProblemDetails for CreateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} #[derive(Debug, PartialEq)] pub enum DeactivateErrorBody { Unauthorized(Problem), NotFound(Error), Conflict(Error), } +impl crate::error::ProblemDetails for DeactivateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} #[derive(Debug, PartialEq)] pub enum GetErrorBody { Unauthorized(Problem), NotFound(Error), } +impl crate::error::ProblemDetails for GetErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} #[derive(Debug, PartialEq)] pub enum UpdateErrorBody { Unauthorized(Problem), NotFound(Error), } +impl crate::error::ProblemDetails for UpdateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} #[derive(Debug, PartialEq)] pub enum ProcessErrorBody { BadRequest(crate::error::UnknownApiBody), @@ -1242,15 +1281,33 @@ pub enum ProcessErrorBody { NotFound(Error), Conflict(Error), } +impl crate::error::ProblemDetails for ProcessErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} #[derive(Debug, PartialEq)] pub enum ListAvailablePaymentMethodsErrorBody { BadRequest(DetailsError), } +impl crate::error::ProblemDetails for ListAvailablePaymentMethodsErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + None + } +} #[derive(Debug, PartialEq)] pub enum CreateApplePaySessionErrorBody { BadRequest(crate::error::UnknownApiBody), NotFound(Error), } +impl crate::error::ProblemDetails for CreateApplePaySessionErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + None + } +} /// Client for the Checkouts API endpoints. #[derive(Debug)] pub struct CheckoutsClient<'a> { @@ -1300,16 +1357,12 @@ impl<'a> CheckoutsClient<'a> { Ok(data) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(ListErrorBody::Unauthorized( - body, - ))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ListErrorBody::Unauthorized) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Create a checkout @@ -1354,32 +1407,30 @@ impl<'a> CheckoutsClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: ErrorExtended = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::Unauthorized( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::FORBIDDEN => { - let body: ErrorForbidden = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::Forbidden( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::Forbidden) + }) + .await) } reqwest::StatusCode::CONFLICT => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::Conflict(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::Conflict) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Deactivate a checkout @@ -1417,28 +1468,24 @@ impl<'a> CheckoutsClient<'a> { Ok(data) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - DeactivateErrorBody::Unauthorized(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(DeactivateErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(DeactivateErrorBody::NotFound( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(DeactivateErrorBody::NotFound) + }) + .await) } reqwest::StatusCode::CONFLICT => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(DeactivateErrorBody::Conflict( - body, - ))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(DeactivateErrorBody::Conflict) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Retrieve a checkout @@ -1475,20 +1522,18 @@ impl<'a> CheckoutsClient<'a> { Ok(data) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::Unauthorized( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Update a checkout @@ -1529,20 +1574,18 @@ impl<'a> CheckoutsClient<'a> { Ok(data) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::Unauthorized( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Process a checkout @@ -1596,35 +1639,32 @@ impl<'a> CheckoutsClient<'a> { Ok(ProcessResponse::Status202(data)) } reqwest::StatusCode::BAD_REQUEST => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::api(ProcessErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + Ok(ProcessErrorBody::BadRequest( + crate::error::UnknownApiBody::from_bytes(raw), + )) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(ProcessErrorBody::Unauthorized( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ProcessErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(ProcessErrorBody::NotFound( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ProcessErrorBody::NotFound) + }) + .await) } reqwest::StatusCode::CONFLICT => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(ProcessErrorBody::Conflict( - body, - ))) - } - _ => { - let body = response.text().await?; - let body = crate::error::UnknownApiBody::from_text(body); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ProcessErrorBody::Conflict) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Get available payment methods @@ -1670,16 +1710,13 @@ impl<'a> CheckoutsClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: DetailsError = response.json().await?; - Err(crate::error::SdkError::api( - ListAvailablePaymentMethodsErrorBody::BadRequest(body), - )) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(ListAvailablePaymentMethodsErrorBody::BadRequest) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Create an Apple Pay session @@ -1728,23 +1765,21 @@ impl<'a> CheckoutsClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::api( - CreateApplePaySessionErrorBody::BadRequest(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + Ok(CreateApplePaySessionErrorBody::BadRequest( + crate::error::UnknownApiBody::from_bytes(raw), + )) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api( - CreateApplePaySessionErrorBody::NotFound(body), - )) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(CreateApplePaySessionErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } } diff --git a/sdk/src/resources/customers.rs b/sdk/src/resources/customers.rs index f26aae7..8eb382f 100644 --- a/sdk/src/resources/customers.rs +++ b/sdk/src/resources/customers.rs @@ -103,24 +103,56 @@ pub enum CreateErrorBody { Forbidden(ErrorForbidden), Conflict(Error), } +impl crate::error::ProblemDetails for CreateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} #[derive(Debug, PartialEq)] pub enum GetErrorBody { Unauthorized(Problem), Forbidden(ErrorForbidden), NotFound(Error), } +impl crate::error::ProblemDetails for GetErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} #[derive(Debug, PartialEq)] pub enum UpdateErrorBody { Unauthorized(Problem), Forbidden(ErrorForbidden), NotFound(Error), } +impl crate::error::ProblemDetails for UpdateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} #[derive(Debug, PartialEq)] pub enum ListPaymentInstrumentsErrorBody { Unauthorized(Problem), Forbidden(ErrorForbidden), NotFound(Error), } +impl crate::error::ProblemDetails for ListPaymentInstrumentsErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} #[derive(Debug, PartialEq)] pub enum DeactivatePaymentInstrumentErrorBody { BadRequest(Error), @@ -128,6 +160,14 @@ pub enum DeactivatePaymentInstrumentErrorBody { Forbidden(ErrorForbidden), NotFound(Error), } +impl crate::error::ProblemDetails for DeactivatePaymentInstrumentErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} /// Client for the Customers API endpoints. #[derive(Debug)] pub struct CustomersClient<'a> { @@ -178,33 +218,32 @@ impl<'a> CustomersClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::api(CreateErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + Ok(CreateErrorBody::BadRequest( + crate::error::UnknownApiBody::from_bytes(raw), + )) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::Unauthorized( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::FORBIDDEN => { - let body: ErrorForbidden = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::Forbidden( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::Forbidden) + }) + .await) } reqwest::StatusCode::CONFLICT => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::Conflict(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::Conflict) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Retrieve a customer @@ -242,24 +281,24 @@ impl<'a> CustomersClient<'a> { Ok(data) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::Unauthorized( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::FORBIDDEN => { - let body: ErrorForbidden = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::Forbidden(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::Forbidden) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Update a customer @@ -301,26 +340,24 @@ impl<'a> CustomersClient<'a> { Ok(data) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::Unauthorized( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::FORBIDDEN => { - let body: ErrorForbidden = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::Forbidden( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::Forbidden) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// List payment instruments @@ -362,28 +399,27 @@ impl<'a> CustomersClient<'a> { Ok(data) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - ListPaymentInstrumentsErrorBody::Unauthorized(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(ListPaymentInstrumentsErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::FORBIDDEN => { - let body: ErrorForbidden = response.json().await?; - Err(crate::error::SdkError::api( - ListPaymentInstrumentsErrorBody::Forbidden(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(ListPaymentInstrumentsErrorBody::Forbidden) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api( - ListPaymentInstrumentsErrorBody::NotFound(body), - )) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(ListPaymentInstrumentsErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Deactivate a payment instrument @@ -424,34 +460,34 @@ impl<'a> CustomersClient<'a> { match status { reqwest::StatusCode::NO_CONTENT => Ok(()), reqwest::StatusCode::BAD_REQUEST => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api( - DeactivatePaymentInstrumentErrorBody::BadRequest(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(DeactivatePaymentInstrumentErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - DeactivatePaymentInstrumentErrorBody::Unauthorized(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(DeactivatePaymentInstrumentErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::FORBIDDEN => { - let body: ErrorForbidden = response.json().await?; - Err(crate::error::SdkError::api( - DeactivatePaymentInstrumentErrorBody::Forbidden(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(DeactivatePaymentInstrumentErrorBody::Forbidden) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api( - DeactivatePaymentInstrumentErrorBody::NotFound(body), - )) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(DeactivatePaymentInstrumentErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } } diff --git a/sdk/src/resources/members.rs b/sdk/src/resources/members.rs index 3d99bce..edfb788 100644 --- a/sdk/src/resources/members.rs +++ b/sdk/src/resources/members.rs @@ -255,21 +255,52 @@ use crate::client::Client; pub enum ListErrorBody { NotFound(Problem), } +impl crate::error::ProblemDetails for ListErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum CreateErrorBody { BadRequest(Problem), NotFound(Problem), TooManyRequests(Problem), } +impl crate::error::ProblemDetails for CreateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + Self::TooManyRequests(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum DeleteErrorBody { Forbidden(Problem), NotFound(Problem), } +impl crate::error::ProblemDetails for DeleteErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Forbidden(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum GetErrorBody { NotFound(Problem), } +impl crate::error::ProblemDetails for GetErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum UpdateErrorBody { BadRequest(Problem), @@ -277,6 +308,16 @@ pub enum UpdateErrorBody { NotFound(Problem), Conflict(Problem), } +impl crate::error::ProblemDetails for UpdateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::Forbidden(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + Self::Conflict(problem) => Some(problem), + } + } +} /// Client for the Members API endpoints. #[derive(Debug)] pub struct MembersClient<'a> { @@ -345,14 +386,12 @@ impl<'a> MembersClient<'a> { Ok(data) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(ListErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ListErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Create a member @@ -396,26 +435,24 @@ impl<'a> MembersClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::NotFound(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::NotFound) + }) + .await) } reqwest::StatusCode::TOO_MANY_REQUESTS => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - CreateErrorBody::TooManyRequests(body), - )) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::TooManyRequests) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Delete a member @@ -454,20 +491,18 @@ impl<'a> MembersClient<'a> { match status { reqwest::StatusCode::OK => Ok(()), reqwest::StatusCode::FORBIDDEN => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(DeleteErrorBody::Forbidden( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(DeleteErrorBody::Forbidden) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(DeleteErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(DeleteErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Retrieve a member @@ -508,14 +543,12 @@ impl<'a> MembersClient<'a> { Ok(data) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Update a member @@ -564,30 +597,30 @@ impl<'a> MembersClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::FORBIDDEN => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::Forbidden( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::Forbidden) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::NotFound(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::NotFound) + }) + .await) } reqwest::StatusCode::CONFLICT => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::Conflict(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::Conflict) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } } diff --git a/sdk/src/resources/memberships.rs b/sdk/src/resources/memberships.rs index 747a8f8..42a4b22 100644 --- a/sdk/src/resources/memberships.rs +++ b/sdk/src/resources/memberships.rs @@ -146,6 +146,14 @@ pub enum ListErrorBody { BadRequest(Problem), Unauthorized(Problem), } +impl crate::error::ProblemDetails for ListErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::Unauthorized(problem) => Some(problem), + } + } +} /// Client for the Memberships API endpoints. #[derive(Debug)] pub struct MembershipsClient<'a> { @@ -226,20 +234,18 @@ impl<'a> MembershipsClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(ListErrorBody::BadRequest(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ListErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(ListErrorBody::Unauthorized( - body, - ))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ListErrorBody::Unauthorized) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } } diff --git a/sdk/src/resources/merchants.rs b/sdk/src/resources/merchants.rs index c0a753b..3cfd8e5 100644 --- a/sdk/src/resources/merchants.rs +++ b/sdk/src/resources/merchants.rs @@ -673,14 +673,35 @@ use crate::client::Client; pub enum GetErrorBody { NotFound(Problem), } +impl crate::error::ProblemDetails for GetErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum ListPersonsErrorBody { NotFound(Problem), } +impl crate::error::ProblemDetails for ListPersonsErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum GetPersonErrorBody { NotFound(Problem), } +impl crate::error::ProblemDetails for GetPersonErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::NotFound(problem) => Some(problem), + } + } +} /// Client for the Merchants API endpoints. #[derive(Debug)] pub struct MerchantsClient<'a> { @@ -727,14 +748,12 @@ impl<'a> MerchantsClient<'a> { Ok(data) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// List Persons @@ -770,16 +789,12 @@ impl<'a> MerchantsClient<'a> { Ok(data) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(ListPersonsErrorBody::NotFound( - body, - ))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ListPersonsErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Get Person @@ -820,16 +835,12 @@ impl<'a> MerchantsClient<'a> { Ok(data) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetPersonErrorBody::NotFound( - body, - ))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetPersonErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } } diff --git a/sdk/src/resources/payouts.rs b/sdk/src/resources/payouts.rs index 9f25806..26b4903 100644 --- a/sdk/src/resources/payouts.rs +++ b/sdk/src/resources/payouts.rs @@ -135,6 +135,14 @@ pub enum ListErrorBody { BadRequest(crate::error::UnknownApiBody), Unauthorized(Problem), } +impl crate::error::ProblemDetails for ListErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} /// Client for the Payouts API endpoints. #[derive(Debug)] pub struct PayoutsClient<'a> { @@ -200,21 +208,20 @@ impl<'a> PayoutsClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::api(ListErrorBody::BadRequest(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + Ok(ListErrorBody::BadRequest( + crate::error::UnknownApiBody::from_bytes(raw), + )) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(ListErrorBody::Unauthorized( - body, - ))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ListErrorBody::Unauthorized) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } } diff --git a/sdk/src/resources/readers.rs b/sdk/src/resources/readers.rs index a7a1623..898b2d0 100644 --- a/sdk/src/resources/readers.rs +++ b/sdk/src/resources/readers.rs @@ -781,25 +781,63 @@ use crate::client::Client; pub enum ListErrorBody { Unauthorized(Problem), } +impl crate::error::ProblemDetails for ListErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum CreateErrorBody { BadRequest(Problem), NotFound(Problem), Conflict(Problem), } +impl crate::error::ProblemDetails for CreateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + Self::Conflict(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum DeleteErrorBody { NotFound(Problem), } +impl crate::error::ProblemDetails for DeleteErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum GetErrorBody { NotFound(Problem), } +impl crate::error::ProblemDetails for GetErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum UpdateErrorBody { Forbidden(Problem), NotFound(Problem), } +impl crate::error::ProblemDetails for UpdateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Forbidden(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum CreateCheckoutErrorBody { BadRequest(Problem), @@ -807,17 +845,44 @@ pub enum CreateCheckoutErrorBody { NotFound(Problem), UnprocessableEntity(Problem), } +impl crate::error::ProblemDetails for CreateCheckoutErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::Unauthorized(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + Self::UnprocessableEntity(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum GetCheckoutErrorBody { Unauthorized(Problem), NotFound(Problem), } +impl crate::error::ProblemDetails for GetCheckoutErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum GetStatusErrorBody { BadRequest(Problem), Unauthorized(Problem), NotFound(Problem), } +impl crate::error::ProblemDetails for GetStatusErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::Unauthorized(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum TerminateCheckoutErrorBody { BadRequest(Problem), @@ -825,6 +890,16 @@ pub enum TerminateCheckoutErrorBody { NotFound(Problem), UnprocessableEntity(Problem), } +impl crate::error::ProblemDetails for TerminateCheckoutErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::Unauthorized(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + Self::UnprocessableEntity(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum CreateGoCheckoutErrorBody { BadRequest(Problem), @@ -832,6 +907,16 @@ pub enum CreateGoCheckoutErrorBody { NotFound(Problem), UnprocessableEntity(Problem), } +impl crate::error::ProblemDetails for CreateGoCheckoutErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::Unauthorized(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + Self::UnprocessableEntity(problem) => Some(problem), + } + } +} /// Client for the Readers API endpoints. #[derive(Debug)] pub struct ReadersClient<'a> { @@ -878,16 +963,12 @@ impl<'a> ReadersClient<'a> { Ok(data) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(ListErrorBody::Unauthorized( - body, - ))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ListErrorBody::Unauthorized) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Create a Reader @@ -927,24 +1008,24 @@ impl<'a> ReadersClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::NotFound(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::NotFound) + }) + .await) } reqwest::StatusCode::CONFLICT => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::Conflict(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::Conflict) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Delete a reader @@ -982,14 +1063,12 @@ impl<'a> ReadersClient<'a> { match status { reqwest::StatusCode::OK => Ok(()), reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(DeleteErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(DeleteErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Retrieve a Reader @@ -1030,14 +1109,12 @@ impl<'a> ReadersClient<'a> { Ok(data) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Update a Reader @@ -1083,20 +1160,18 @@ impl<'a> ReadersClient<'a> { Ok(data) } reqwest::StatusCode::FORBIDDEN => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::Forbidden( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::Forbidden) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Create a Reader Checkout @@ -1152,34 +1227,32 @@ impl<'a> ReadersClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - CreateCheckoutErrorBody::BadRequest(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateCheckoutErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - CreateCheckoutErrorBody::Unauthorized(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(CreateCheckoutErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - CreateCheckoutErrorBody::NotFound(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateCheckoutErrorBody::NotFound) + }) + .await) } reqwest::StatusCode::UNPROCESSABLE_ENTITY => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - CreateCheckoutErrorBody::UnprocessableEntity(body), - )) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(CreateCheckoutErrorBody::UnprocessableEntity) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Get a Reader Checkout @@ -1223,22 +1296,18 @@ impl<'a> ReadersClient<'a> { Ok(data) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - GetCheckoutErrorBody::Unauthorized(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetCheckoutErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetCheckoutErrorBody::NotFound( - body, - ))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetCheckoutErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Get a Reader Status @@ -1299,28 +1368,24 @@ impl<'a> ReadersClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetStatusErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetStatusErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - GetStatusErrorBody::Unauthorized(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetStatusErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetStatusErrorBody::NotFound( - body, - ))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetStatusErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Terminate a Reader Checkout @@ -1374,34 +1439,33 @@ impl<'a> ReadersClient<'a> { match status { reqwest::StatusCode::ACCEPTED => Ok(()), reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - TerminateCheckoutErrorBody::BadRequest(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(TerminateCheckoutErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - TerminateCheckoutErrorBody::Unauthorized(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(TerminateCheckoutErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - TerminateCheckoutErrorBody::NotFound(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(TerminateCheckoutErrorBody::NotFound) + }) + .await) } reqwest::StatusCode::UNPROCESSABLE_ENTITY => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - TerminateCheckoutErrorBody::UnprocessableEntity(body), - )) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(TerminateCheckoutErrorBody::UnprocessableEntity) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Create a Go Reader Payment @@ -1449,34 +1513,33 @@ impl<'a> ReadersClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - CreateGoCheckoutErrorBody::BadRequest(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(CreateGoCheckoutErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - CreateGoCheckoutErrorBody::Unauthorized(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(CreateGoCheckoutErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - CreateGoCheckoutErrorBody::NotFound(body), - )) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateGoCheckoutErrorBody::NotFound) + }) + .await) } reqwest::StatusCode::UNPROCESSABLE_ENTITY => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - CreateGoCheckoutErrorBody::UnprocessableEntity(body), - )) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw) + .map(CreateGoCheckoutErrorBody::UnprocessableEntity) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } } diff --git a/sdk/src/resources/receipts.rs b/sdk/src/resources/receipts.rs index 9bb7234..f9c4b70 100644 --- a/sdk/src/resources/receipts.rs +++ b/sdk/src/resources/receipts.rs @@ -429,6 +429,14 @@ pub enum GetErrorBody { Unauthorized(Problem), NotFound(Error), } +impl crate::error::ProblemDetails for GetErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} /// Client for the Receipts API endpoints. #[derive(Debug)] pub struct ReceiptsClient<'a> { @@ -482,24 +490,24 @@ impl<'a> ReceiptsClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::BadRequest(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::Unauthorized( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } } diff --git a/sdk/src/resources/roles.rs b/sdk/src/resources/roles.rs index c4c6645..23ad69f 100644 --- a/sdk/src/resources/roles.rs +++ b/sdk/src/resources/roles.rs @@ -118,25 +118,63 @@ use crate::client::Client; pub enum ListErrorBody { NotFound(Problem), } +impl crate::error::ProblemDetails for ListErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum CreateErrorBody { BadRequest(Problem), NotFound(Problem), } +impl crate::error::ProblemDetails for CreateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum DeleteErrorBody { BadRequest(Problem), NotFound(Problem), } +impl crate::error::ProblemDetails for DeleteErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum GetErrorBody { NotFound(Problem), } +impl crate::error::ProblemDetails for GetErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::NotFound(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum UpdateErrorBody { BadRequest(Problem), NotFound(Problem), } +impl crate::error::ProblemDetails for UpdateErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + } + } +} /// Client for the Roles API endpoints. #[derive(Debug)] pub struct RolesClient<'a> { @@ -183,14 +221,12 @@ impl<'a> RolesClient<'a> { Ok(data) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(ListErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ListErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Create a role @@ -229,20 +265,18 @@ impl<'a> RolesClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(CreateErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(CreateErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Delete a role @@ -281,20 +315,18 @@ impl<'a> RolesClient<'a> { match status { reqwest::StatusCode::OK => Ok(()), reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(DeleteErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(DeleteErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(DeleteErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(DeleteErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Retrieve a role @@ -335,14 +367,12 @@ impl<'a> RolesClient<'a> { Ok(data) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Update a role @@ -388,20 +418,18 @@ impl<'a> RolesClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(UpdateErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(UpdateErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } } diff --git a/sdk/src/resources/transactions.rs b/sdk/src/resources/transactions.rs index f0f3109..8ff6b45 100644 --- a/sdk/src/resources/transactions.rs +++ b/sdk/src/resources/transactions.rs @@ -975,16 +975,43 @@ pub enum RefundErrorBody { Conflict(Problem), UnprocessableEntity(Problem), } +impl crate::error::ProblemDetails for RefundErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::BadRequest(problem) => Some(problem), + Self::Forbidden(problem) => Some(problem), + Self::NotFound(problem) => Some(problem), + Self::Conflict(problem) => Some(problem), + Self::UnprocessableEntity(problem) => Some(problem), + } + } +} #[derive(Debug, PartialEq)] pub enum GetErrorBody { Unauthorized(Problem), NotFound(Error), } +impl crate::error::ProblemDetails for GetErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} #[derive(Debug, PartialEq)] pub enum ListErrorBody { BadRequest(Error), Unauthorized(Problem), } +impl crate::error::ProblemDetails for ListErrorBody { + fn problem(&self) -> Option<&crate::resources::common::Problem> { + match self { + Self::Unauthorized(problem) => Some(problem), + _ => None, + } + } +} /// Client for the Transactions API endpoints. #[derive(Debug)] pub struct TransactionsClient<'a> { @@ -1046,36 +1073,36 @@ impl<'a> TransactionsClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(RefundErrorBody::BadRequest( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(RefundErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::FORBIDDEN => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(RefundErrorBody::Forbidden( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(RefundErrorBody::Forbidden) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(RefundErrorBody::NotFound(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(RefundErrorBody::NotFound) + }) + .await) } reqwest::StatusCode::CONFLICT => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(RefundErrorBody::Conflict(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(RefundErrorBody::Conflict) + }) + .await) } reqwest::StatusCode::UNPROCESSABLE_ENTITY => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api( - RefundErrorBody::UnprocessableEntity(body), - )) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(RefundErrorBody::UnprocessableEntity) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// Retrieve a transaction @@ -1129,20 +1156,18 @@ impl<'a> TransactionsClient<'a> { Ok(data) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::Unauthorized( - body, - ))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::Unauthorized) + }) + .await) } reqwest::StatusCode::NOT_FOUND => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(GetErrorBody::NotFound(body))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(GetErrorBody::NotFound) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } /// List transactions @@ -1224,20 +1249,18 @@ impl<'a> TransactionsClient<'a> { Ok(data) } reqwest::StatusCode::BAD_REQUEST => { - let body: Error = response.json().await?; - Err(crate::error::SdkError::api(ListErrorBody::BadRequest(body))) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ListErrorBody::BadRequest) + }) + .await) } reqwest::StatusCode::UNAUTHORIZED => { - let body: Problem = response.json().await?; - Err(crate::error::SdkError::api(ListErrorBody::Unauthorized( - body, - ))) - } - _ => { - let body_bytes = response.bytes().await?; - let body = crate::error::UnknownApiBody::from_bytes(body_bytes.as_ref()); - Err(crate::error::SdkError::unexpected(status, body)) + Err(crate::error::SdkError::from_response(response, |raw| { + serde_json::from_slice::(raw).map(ListErrorBody::Unauthorized) + }) + .await) } + _ => Err(crate::error::SdkError::unexpected_response(response).await), } } } diff --git a/sdk/tests/api_errors.rs b/sdk/tests/api_errors.rs new file mode 100644 index 0000000..b948173 --- /dev/null +++ b/sdk/tests/api_errors.rs @@ -0,0 +1,64 @@ +use sumup::Client; +use wiremock::matchers::{method, path}; +use wiremock::{Mock, MockServer, ResponseTemplate}; + +#[tokio::test] +async fn documented_problem_preserves_http_context() { + let server = MockServer::start().await; + let raw = r#"{"type":"about:blank","detail":"Access token expired"}"#; + Mock::given(method("GET")) + .and(path("/v0.1/checkouts/checkout")) + .respond_with( + ResponseTemplate::new(401) + .set_body_raw(raw, "application/problem+json") + .insert_header("Retry-After", "10"), + ) + .mount(&server) + .await; + let client = Client::new().with_base_url(server.uri()); + let error = client.checkouts().get("checkout").await.unwrap_err(); + assert_eq!(error.status(), Some(reqwest::StatusCode::UNAUTHORIZED)); + assert_eq!( + error.problem().unwrap().detail.as_deref(), + Some("Access token expired") + ); + assert_eq!(error.headers().unwrap()["retry-after"], "10"); + assert_eq!(error.raw_body().unwrap(), raw.as_bytes()); + assert!(error.body().is_some()); +} + +#[tokio::test] +async fn malformed_documented_error_remains_an_http_failure() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(401).set_body_raw("{invalid", "application/problem+json"), + ) + .mount(&server) + .await; + let client = Client::new().with_base_url(server.uri()); + let error = client.checkouts().get("checkout").await.unwrap_err(); + assert_eq!(error.status(), Some(reqwest::StatusCode::UNAUTHORIZED)); + assert!(error.problem().is_none()); + assert_eq!(error.raw_body().unwrap(), b"{invalid"); + assert!(matches!(error, sumup::error::SdkError::Unexpected(_))); +} + +#[tokio::test] +async fn undocumented_problem_has_typed_details() { + let server = MockServer::start().await; + Mock::given(method("GET")) + .respond_with( + ResponseTemplate::new(502) + .set_body_json(serde_json::json!({"type": "about:blank", "detail": "Unavailable"})), + ) + .mount(&server) + .await; + let client = Client::new().with_base_url(server.uri()); + let error = client.checkouts().get("checkout").await.unwrap_err(); + assert_eq!(error.status(), Some(reqwest::StatusCode::BAD_GATEWAY)); + assert_eq!( + error.problem().unwrap().detail.as_deref(), + Some("Unavailable") + ); +} From fbc40935124e5568ae4cec7c74a4b8cb5c4a54d1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Dzivjak?= Date: Mon, 26 Oct 2026 18:25:02 +0100 Subject: [PATCH 2/3] fix: retain HTTP context for response body failures Represent interrupted response bodies separately from connection failures. Keep the received status and headers alongside the original cause for documented and unexpected errors. --- sdk/src/error.rs | 30 ++++++++++++++++++++++++++++-- sdk/src/lib.rs | 5 ++++- sdk/tests/api_errors.rs | 38 ++++++++++++++++++++++++++++++++++++++ 3 files changed, 70 insertions(+), 3 deletions(-) diff --git a/sdk/src/error.rs b/sdk/src/error.rs index 535f4c8..ef8ac5b 100644 --- a/sdk/src/error.rs +++ b/sdk/src/error.rs @@ -11,6 +11,8 @@ pub enum SdkError { InvalidRequest(String), /// Errors originating from the underlying HTTP client (network, TLS, etc.). Network(reqwest::Error), + /// An HTTP response arrived, but its body could not be read. + Response(Box), /// The server returned an API response with an expected error payload. Api(Box>), /// The server returned an unexpected status or payload. @@ -33,7 +35,13 @@ impl SdkError { let headers = response.headers().clone(); let raw_body = match response.bytes().await { Ok(bytes) => bytes.to_vec(), - Err(error) => return Self::Network(error), + Err(source) => { + return Self::Response(Box::new(ResponseError { + status, + headers, + source, + })); + } }; match decode(&raw_body) { Ok(body) => Self::Api(Box::new(ApiErrorResponse { @@ -63,7 +71,11 @@ impl SdkError { body: UnknownApiBody::from_bytes(&bytes), raw_body: bytes.to_vec(), })), - Err(error) => Self::Network(error), + Err(source) => Self::Response(Box::new(ResponseError { + status, + headers, + source, + })), } } @@ -71,6 +83,7 @@ impl SdkError { pub fn status(&self) -> Option { match self { Self::Network(err) => err.status(), + Self::Response(error) => Some(error.status), Self::Unexpected(response) => Some(response.status), Self::Api(response) => Some(response.status), Self::InvalidRequest(_) => None, @@ -103,6 +116,7 @@ impl SdkError { /// Returns the response headers for an API failure. pub fn headers(&self) -> Option<&reqwest::header::HeaderMap> { match self { + Self::Response(error) => Some(&error.headers), Self::Api(response) => Some(&response.headers), Self::Unexpected(response) => Some(&response.headers), _ => None, @@ -133,6 +147,9 @@ where match self { Self::InvalidRequest(reason) => write!(f, "invalid request: {reason}"), Self::Network(err) => write!(f, "network error: {}", err), + Self::Response(error) => { + write!(f, "response error ({}): {}", error.status, error.source) + } Self::Api(response) => { write!(f, "API error ({}): {:?}", response.status, response.body) } @@ -154,11 +171,20 @@ where fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { Self::Network(err) => Some(err), + Self::Response(error) => Some(&error.source), _ => None, } } } +/// An HTTP response whose body could not be read. +#[derive(Debug)] +pub struct ResponseError { + pub status: reqwest::StatusCode, + pub headers: reqwest::header::HeaderMap, + pub source: reqwest::Error, +} + /// An API response with typed error details and its original HTTP context. #[derive(Debug)] pub struct ApiErrorResponse { diff --git a/sdk/src/lib.rs b/sdk/src/lib.rs index 22be591..6d36566 100644 --- a/sdk/src/lib.rs +++ b/sdk/src/lib.rs @@ -150,6 +150,7 @@ //! Err(SdkError::Unexpected(response)) => { //! eprintln!("unexpected {} response: {}", response.status, response.body); //! } +//! Err(SdkError::Response(err)) => eprintln!("could not read response ({}): {}", err.status, err.source), //! Err(SdkError::Network(err)) => panic!("network error: {}", err), //! Err(SdkError::InvalidRequest(reason)) => eprintln!("invalid request: {}", reason), //! } @@ -194,7 +195,9 @@ pub mod resources; pub use crate::resources::*; pub use auth::Authorization; pub use client::Client; -pub use error::{ApiErrorResponse, ProblemDetails, SdkError, SdkResult, UnknownApiBody}; +pub use error::{ + ApiErrorResponse, ProblemDetails, ResponseError, SdkError, SdkResult, UnknownApiBody, +}; pub use nullable::Nullable; pub use secret::Secret; pub use version::VERSION; diff --git a/sdk/tests/api_errors.rs b/sdk/tests/api_errors.rs index b948173..41ecf8c 100644 --- a/sdk/tests/api_errors.rs +++ b/sdk/tests/api_errors.rs @@ -62,3 +62,41 @@ async fn undocumented_problem_has_typed_details() { Some("Unavailable") ); } + +#[tokio::test] +async fn interrupted_error_bodies_preserve_http_context() { + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader}; + for status in [401, 502] { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let server = tokio::spawn(async move { + let (stream, _) = listener.accept().await.unwrap(); + let mut stream = BufReader::new(stream); + loop { + let mut line = String::new(); + assert!(stream.read_line(&mut line).await.unwrap() > 0); + if line == "\r\n" { + break; + } + } + // The declared body length is deliberately larger than the bytes sent. + let response = format!( + "HTTP/1.1 {status} Error\r\nContent-Length: 100\r\nRetry-After: 7\r\nConnection: close\r\n\r\nbad" + ); + stream + .get_mut() + .write_all(response.as_bytes()) + .await + .unwrap(); + }); + let client = Client::new().with_base_url(format!("http://{address}")); + let error = client.checkouts().get("checkout").await.unwrap_err(); + server.await.unwrap(); + assert_eq!(error.status().unwrap().as_u16(), status); + assert_eq!(error.headers().unwrap()["retry-after"], "7"); + assert!(matches!(error, sumup::SdkError::Response(_))); + assert!(std::error::Error::source(&error).is_some()); + assert!(error.problem().is_none()); + assert!(error.raw_body().is_none()); + } +} From 6987e3fb3c7e5640501080e972b1e9581fa210f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Dzivjak?= Date: Mon, 26 Oct 2026 18:47:50 +0100 Subject: [PATCH 3/3] fix: expose Problem details from untyped error bodies Keep typed Problem access available when an endpoint does not describe its error body. Simplify the README and API documentation around the common error handling path. --- CONTRIBUTING.md | 25 +++++++++++++- README.md | 62 ++++++++++------------------------ codegen/src/operation.rs | 3 ++ sdk/src/lib.rs | 29 ++++++---------- sdk/src/resources/checkouts.rs | 6 +++- sdk/src/resources/customers.rs | 1 + sdk/src/resources/payouts.rs | 2 +- sdk/tests/api_errors.rs | 27 +++++++++++++++ 8 files changed, 89 insertions(+), 66 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 277c05e..56cc672 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,28 @@ -## Generate code +# Contributing + +## Code generation + +Regenerate the Rust SDK from `openapi.json` with: ```sh cargo xtask generate ``` + +Generate the deterministic JSON catalog of developer-portal code samples with: + +```sh +cargo xtask generate-code-samples +``` + +The default output is the ignored `code-samples.json` at the repository root. +Use `--output ` to write it elsewhere. Every sample is a complete Rust +program, and named OpenAPI request examples are emitted as separate catalog +entries. To regenerate twice and compile every program against the local SDK, +run: + +```sh +cargo xtask validate-code-samples +``` + +Published releases synchronize this catalog to +`sumup/sumup-developer` as `src/codesamples/rust.json`. diff --git a/README.md b/README.md index 7e815d6..349ae86 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,23 @@ let client = Client::default() .with_authorization(Authorization::api_key("your_api_key")); ``` +## Handling errors + +API errors retain their HTTP status, headers, and original response bytes. Read typed +Problem details directly when available: + +```rust +if let Err(error) = client.checkouts().get("your-checkout-id").await { + if let Some(problem) = error.problem() { + println!("{}: {}", problem.r#type, problem.detail.as_deref().unwrap_or("Request failed")); + } + println!("{:?}", error.status()); +} +``` + +Use `status()` and `headers()` to inspect the HTTP response, `raw_body()` for its +original bytes, and `body()` for other typed error details. + ## HTTP Configuration The SDK uses `reqwest` as its HTTP transport. You can provide a configured @@ -110,49 +127,6 @@ You can find all examples under [examples/](/examples/). To run an example, use: cargo run --example checkout_card_reader ``` -## Code generation - -Regenerate the Rust SDK from `openapi.json` with: - -```sh -cargo xtask generate -``` - -Generate the deterministic JSON catalog of developer-portal code samples with: - -```sh -cargo xtask generate-code-samples -``` - -The default output is the ignored `code-samples.json` at the repository root. -Use `--output ` to write it elsewhere. Every sample is a complete Rust -program, and named OpenAPI request examples are emitted as separate catalog -entries. To regenerate twice and compile every program against the local SDK, -run: - -```sh -cargo xtask validate-code-samples -``` - -Published releases synchronize this catalog to -`sumup/sumup-developer` as `src/codesamples/rust.json`. +For development instructions, see [Contributing](CONTRIBUTING.md). [docs-badge]: https://img.shields.io/badge/SumUp-documentation-white.svg?logo=data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMjQiIGhlaWdodD0iMjQiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0ibm9uZSIgY29sb3I9IndoaXRlIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPgogICAgPHBhdGggZD0iTTIyLjI5IDBIMS43Qy43NyAwIDAgLjc3IDAgMS43MVYyMi4zYzAgLjkzLjc3IDEuNyAxLjcxIDEuN0gyMi4zYy45NCAwIDEuNzEtLjc3IDEuNzEtMS43MVYxLjdDMjQgLjc3IDIzLjIzIDAgMjIuMjkgMFptLTcuMjIgMTguMDdhNS42MiA1LjYyIDAgMCAxLTcuNjguMjQuMzYuMzYgMCAwIDEtLjAxLS40OWw3LjQ0LTcuNDRhLjM1LjM1IDAgMCAxIC40OSAwIDUuNiA1LjYgMCAwIDEtLjI0IDcuNjlabTEuNTUtMTEuOS03LjQ0IDcuNDVhLjM1LjM1IDAgMCAxLS41IDAgNS42MSA1LjYxIDAgMCAxIDcuOS03Ljk2bC4wMy4wM2MuMTMuMTMuMTQuMzUuMDEuNDlaIiBmaWxsPSJjdXJyZW50Q29sb3IiLz4KPC9zdmc+ - -## Handling errors - -API errors retain their HTTP status, headers, and original response bytes. Read typed -Problem details directly when available: - -```rust -if let Err(error) = client.checkouts().get("your-checkout-id").await { - if let Some(problem) = error.problem() { - println!("{}: {:?}", problem.r#type, problem.detail); - } - println!("{:?}", error.status()); -} -``` - -Use `body()` for the endpoint's typed error enum, `headers()` for response headers, -and `raw_body()` for the original bytes. When matching `SdkError::Api(response)`, -the typed body is in `response.body`. diff --git a/codegen/src/operation.rs b/codegen/src/operation.rs index 7d08e07..3f2e071 100644 --- a/codegen/src/operation.rs +++ b/codegen/src/operation.rs @@ -730,6 +730,9 @@ fn generate_error_handling( } BodyKind::Unknown => { variant_defs.push(quote! { #variant_ident(crate::error::UnknownApiBody), }); + problem_arms.push(quote! { + Self::#variant_ident(body) => crate::error::ProblemDetails::problem(body), + }); } BodyKind::Empty => { variant_defs.push(quote! { #variant_ident, }); diff --git a/sdk/src/lib.rs b/sdk/src/lib.rs index 6d36566..65bebac 100644 --- a/sdk/src/lib.rs +++ b/sdk/src/lib.rs @@ -129,34 +129,25 @@ //! //! ## Error Handling //! -//! All SDK calls return a [`SdkResult`] whose error side is a [`SdkError`]. When the -//! SumUp API responds with a non-success status, the SDK builds an -//! `SdkError::Api` containing an endpoint-specific payload (e.g. a `Unauthorized` -//! enum variant). Any undocumented status codes fall back to -//! `SdkError::Unexpected`, which preserves the HTTP status and best-effort body -//! parsing. Requests rejected by local validation return `SdkError::InvalidRequest`. -//! You can inspect failures like this: +//! Failed calls return a [`SdkError`]. Use `problem()` to read typed Problem details +//! when the API provides them: //! //! ```no_run -//! # use sumup::{Client, error::SdkError}; -//! # use sumup::resources::checkouts::ListErrorBody; +//! # use sumup::Client; //! # async fn example() { //! let client = Client::default(); -//! match client.checkouts().list(Default::default()).await { -//! Ok(checkouts) => println!("retrieved {} checkouts", checkouts.len()), -//! Err(SdkError::Api(response)) => match response.body { -//! ListErrorBody::Unauthorized(details) => eprintln!("unauthorized: {:?}", details), -//! }, -//! Err(SdkError::Unexpected(response)) => { -//! eprintln!("unexpected {} response: {}", response.status, response.body); +//! if let Err(error) = client.checkouts().get("your-checkout-id").await { +//! if let Some(problem) = error.problem() { +//! eprintln!("{}: {}", problem.r#type, problem.detail.as_deref().unwrap_or("Request failed")); //! } -//! Err(SdkError::Response(err)) => eprintln!("could not read response ({}): {}", err.status, err.source), -//! Err(SdkError::Network(err)) => panic!("network error: {}", err), -//! Err(SdkError::InvalidRequest(reason)) => eprintln!("invalid request: {}", reason), +//! eprintln!("{error}"); //! } //! # } //! ``` //! +//! Use [`SdkError::status`], [`SdkError::headers`], and [`SdkError::raw_body`] +//! to inspect the HTTP response. [`SdkError::body`] provides other typed error details. +//! //! ## Features //! //! - **chrono** (default): Use chrono for datetime types diff --git a/sdk/src/resources/checkouts.rs b/sdk/src/resources/checkouts.rs index 37c0cdd..4fbb8d3 100644 --- a/sdk/src/resources/checkouts.rs +++ b/sdk/src/resources/checkouts.rs @@ -1284,6 +1284,7 @@ pub enum ProcessErrorBody { impl crate::error::ProblemDetails for ProcessErrorBody { fn problem(&self) -> Option<&crate::resources::common::Problem> { match self { + Self::BadRequest(body) => crate::error::ProblemDetails::problem(body), Self::Unauthorized(problem) => Some(problem), _ => None, } @@ -1305,7 +1306,10 @@ pub enum CreateApplePaySessionErrorBody { } impl crate::error::ProblemDetails for CreateApplePaySessionErrorBody { fn problem(&self) -> Option<&crate::resources::common::Problem> { - None + match self { + Self::BadRequest(body) => crate::error::ProblemDetails::problem(body), + _ => None, + } } } /// Client for the Checkouts API endpoints. diff --git a/sdk/src/resources/customers.rs b/sdk/src/resources/customers.rs index 25e6121..41da2cf 100644 --- a/sdk/src/resources/customers.rs +++ b/sdk/src/resources/customers.rs @@ -122,6 +122,7 @@ pub enum CreateErrorBody { impl crate::error::ProblemDetails for CreateErrorBody { fn problem(&self) -> Option<&crate::resources::common::Problem> { match self { + Self::BadRequest(body) => crate::error::ProblemDetails::problem(body), Self::Unauthorized(problem) => Some(problem), _ => None, } diff --git a/sdk/src/resources/payouts.rs b/sdk/src/resources/payouts.rs index 26b4903..2509608 100644 --- a/sdk/src/resources/payouts.rs +++ b/sdk/src/resources/payouts.rs @@ -138,8 +138,8 @@ pub enum ListErrorBody { impl crate::error::ProblemDetails for ListErrorBody { fn problem(&self) -> Option<&crate::resources::common::Problem> { match self { + Self::BadRequest(body) => crate::error::ProblemDetails::problem(body), Self::Unauthorized(problem) => Some(problem), - _ => None, } } } diff --git a/sdk/tests/api_errors.rs b/sdk/tests/api_errors.rs index 41ecf8c..b32eca7 100644 --- a/sdk/tests/api_errors.rs +++ b/sdk/tests/api_errors.rs @@ -100,3 +100,30 @@ async fn interrupted_error_bodies_preserve_http_context() { assert!(error.raw_body().is_none()); } } + +#[tokio::test] +async fn documented_error_without_a_body_schema_exposes_problem_details() { + let server = MockServer::start().await; + Mock::given(method("POST")) + .and(path("/v0.1/customers")) + .respond_with(ResponseTemplate::new(400).set_body_json(serde_json::json!({ + "type": "about:blank", "detail": "Invalid customer" + }))) + .mount(&server) + .await; + let client = Client::new().with_base_url(server.uri()); + let error = client + .customers() + .create(sumup::resources::customers::CreateRequest { + customer_id: "customer".into(), + personal_details: None, + }) + .await + .unwrap_err(); + assert_eq!( + error.problem().unwrap().detail.as_deref(), + Some("Invalid customer") + ); + assert_eq!(error.status(), Some(reqwest::StatusCode::BAD_REQUEST)); + assert!(error.body().is_some()); +}