From e57ed7ff40ee0601cfd100f19e7fbb05da6bbd4c 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: expose typed Problem details and original error responses Expose typed Problem details and preserve error response context. Add focused regression coverage and concise integration examples. --- README.md | 17 ++++++++ src/Exception/ApiException.php | 21 +++++++++- src/Exception/UnexpectedApiException.php | 5 ++- src/HttpClient/GuzzleClient.php | 2 +- src/ResponseDecoder.php | 14 +++++-- tests/ProblemExceptionTest.php | 52 ++++++++++++++++++++++++ 6 files changed, 104 insertions(+), 7 deletions(-) create mode 100644 tests/ProblemExceptionTest.php diff --git a/README.md b/README.md index 72fe5aa9..562e87cb 100644 --- a/README.md +++ b/README.md @@ -169,3 +169,20 @@ For information about the license see the [license](https://github.com/sumup/sum ## Contact Us If you have found a bug or you lack some functionality please [open an issue](https://github.com/sumup/sumup-php/issues/new). If you have other issues when integrating with SumUp's API you can send an email to [integration@sumup.com](mailto:integration@sumup.com). + +## Problem details + +API errors expose typed Problem details when available: + +```php +try { + $checkout = $sumup->checkouts()->get('your-checkout-id'); +} catch (\SumUp\Exception\ApiException $error) { + if (($problem = $error->getProblem()) !== null) { + echo $problem->type . ': ' . $problem->detail; + } +} +``` + +Use `getResponseBody()` for other error details. `getResponse()` provides the original +response, including its headers and text through `getHeaders()` and `getRawBody()`. diff --git a/src/Exception/ApiException.php b/src/Exception/ApiException.php index 7babef8b..fd09bf85 100644 --- a/src/Exception/ApiException.php +++ b/src/Exception/ApiException.php @@ -2,6 +2,9 @@ namespace SumUp\Exception; +use SumUp\HttpClient\Response; +use SumUp\Types\Problem; + /** * Represents an API error decoded from a non-2xx response. */ @@ -17,17 +20,21 @@ class ApiException extends SDKException */ protected ?string $path; + private ?Response $response; + public function __construct( string $message = '', int $statusCode = 0, mixed $responseBody = null, ?string $httpMethod = null, ?string $path = null, - ?\Throwable $previous = null + ?\Throwable $previous = null, + ?Response $response = null ) { parent::__construct($message, $statusCode, $responseBody, $previous); $this->httpMethod = $httpMethod; $this->path = $path; + $this->response = $response; } public function getHttpMethod(): ?string @@ -39,4 +46,16 @@ public function getPath(): ?string { return $this->path; } + + /** Typed Problem details, when the API returned a Problem response. */ + public function getProblem(): ?Problem + { + $body = $this->getResponseBody(); + return $body instanceof Problem ? $body : null; + } + + public function getResponse(): ?Response + { + return $this->response; + } } diff --git a/src/Exception/UnexpectedApiException.php b/src/Exception/UnexpectedApiException.php index c5b9cadc..0a5117a0 100644 --- a/src/Exception/UnexpectedApiException.php +++ b/src/Exception/UnexpectedApiException.php @@ -22,9 +22,10 @@ public function __construct( ?string $path = null, ?array $headers = null, ?string $rawResponseBody = null, - ?\Throwable $previous = null + ?\Throwable $previous = null, + ?\SumUp\HttpClient\Response $response = null ) { - parent::__construct($message, $statusCode, $responseBody, $httpMethod, $path, $previous); + parent::__construct($message, $statusCode, $responseBody, $httpMethod, $path, $previous, $response); $this->rawResponseBody = $rawResponseBody; $this->errorEnvelope = new ErrorEnvelope( $statusCode, diff --git a/src/HttpClient/GuzzleClient.php b/src/HttpClient/GuzzleClient.php index 125b3ed9..39302559 100644 --- a/src/HttpClient/GuzzleClient.php +++ b/src/HttpClient/GuzzleClient.php @@ -114,7 +114,7 @@ function ($retry) use ($backoffMs) { // Guzzle 8 exposes getResponse() only on response-bearing exceptions. $response = method_exists($exception, 'getResponse') ? $exception->getResponse() : null; if (!$response instanceof \Psr\Http\Message\ResponseInterface) { - throw new ConnectionException($exception->getMessage(), $exception->getCode()); + throw new ConnectionException($exception->getMessage(), $exception->getCode(), null, $exception); } } diff --git a/src/ResponseDecoder.php b/src/ResponseDecoder.php index 5a0c5db1..bc905071 100644 --- a/src/ResponseDecoder.php +++ b/src/ResponseDecoder.php @@ -38,7 +38,11 @@ public static function decodeOrThrow( } if (self::hasDescriptorForStatus($errorDescriptors, $statusCode)) { - $decodedErrorBody = self::decode($response, $errorDescriptors); + try { + $decodedErrorBody = self::decode($response, $errorDescriptors); + } catch (\TypeError | \ReflectionException | \InvalidArgumentException $exception) { + $decodedErrorBody = $response->getBody(); + } $message = self::extractErrorMessage($decodedErrorBody, self::defaultErrorMessage($statusCode)); throw new ApiException( @@ -46,7 +50,9 @@ public static function decodeOrThrow( $statusCode, $decodedErrorBody, $httpMethod, - $path + $path, + null, + $response ); } @@ -60,7 +66,9 @@ public static function decodeOrThrow( $httpMethod, $path, $response->getHeaders(), - $response->getRawBody() + $response->getRawBody(), + null, + $response ); } diff --git a/tests/ProblemExceptionTest.php b/tests/ProblemExceptionTest.php new file mode 100644 index 00000000..21850c9b --- /dev/null +++ b/tests/ProblemExceptionTest.php @@ -0,0 +1,52 @@ + 'about:blank', 'detail' => 'Invalid amount']; + $response = new Response(400, $body, ['Retry-After' => ['10']], json_encode($body)); + try { + ResponseDecoder::decodeOrThrow($response, null, ['400' => ['type' => 'class', 'class' => Problem::class]]); + self::fail('Expected API error'); + } catch (ApiException $error) { + self::assertInstanceOf(Problem::class, $error->getProblem()); + self::assertSame($error->getResponseBody(), $error->getProblem()); + self::assertSame('Invalid amount', $error->getProblem()->detail); + self::assertSame($response, $error->getResponse()); + } + } + + public function testInvalidProblemRemainsAnApiError(): void + { + $body = ['type' => null]; + $response = new Response(400, $body); + try { + ResponseDecoder::decodeOrThrow($response, null, ['400' => ['type' => 'class', 'class' => Problem::class]]); + self::fail('Expected API error'); + } catch (ApiException $error) { + self::assertNull($error->getProblem()); + self::assertSame($body, $error->getResponseBody()); + } + } + + public function testUnexpectedResponsesKeepTheirOriginalBody(): void + { + $response = new Response(502, 'Bad gateway', [], 'Bad gateway'); + try { + ResponseDecoder::decodeOrThrow($response); + self::fail('Expected API error'); + } catch (UnexpectedApiException $error) { + self::assertNull($error->getProblem()); + self::assertSame($response, $error->getResponse()); + self::assertSame('Bad gateway', $error->getResponse()->getRawBody()); + } + } +} From df5ad6d70fb3a66fa87004add0ba5bc1abee627d 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: preserve malformed Problem responses as API errors Fall back to the original body for incomplete or invalid Problem data. Avoid array-to-string warnings during hydration and include Problem details or titles in error messages. --- src/Hydrator.php | 3 +++ src/ResponseDecoder.php | 6 +++++- tests/ProblemExceptionTest.php | 23 ++++++++++++++++++----- 3 files changed, 26 insertions(+), 6 deletions(-) diff --git a/src/Hydrator.php b/src/Hydrator.php index b30b9a37..6992d833 100644 --- a/src/Hydrator.php +++ b/src/Hydrator.php @@ -112,6 +112,9 @@ private static function castValue($value, ReflectionProperty $property) case 'bool': return (bool) $value; case 'string': + if (!is_scalar($value)) { + throw new \InvalidArgumentException('Expected a scalar value for ' . $property->getName()); + } return (string) $value; case 'array': return self::castArrayValue($value, $property); diff --git a/src/ResponseDecoder.php b/src/ResponseDecoder.php index bc905071..6007a08d 100644 --- a/src/ResponseDecoder.php +++ b/src/ResponseDecoder.php @@ -5,6 +5,7 @@ use SumUp\Exception\ApiException; use SumUp\Exception\UnexpectedApiException; use SumUp\HttpClient\Response; +use SumUp\Types\Problem; /** * Converts HTTP responses into SDK models or scalar values. @@ -40,6 +41,9 @@ public static function decodeOrThrow( if (self::hasDescriptorForStatus($errorDescriptors, $statusCode)) { try { $decodedErrorBody = self::decode($response, $errorDescriptors); + if ($decodedErrorBody instanceof Problem && !isset($decodedErrorBody->type)) { + $decodedErrorBody = $response->getBody(); + } } catch (\TypeError | \ReflectionException | \InvalidArgumentException $exception) { $decodedErrorBody = $response->getBody(); } @@ -236,7 +240,7 @@ private static function defaultUnexpectedErrorMessage(int $statusCode): string */ private static function extractErrorMessage($body, string $defaultMessage): string { - foreach (['message', 'error_message', 'error_description', 'error'] as $key) { + foreach (['detail', 'title', 'message', 'error_message', 'error_description', 'error'] as $key) { $value = self::readField($body, $key); if (is_string($value) && $value !== '') { return $value; diff --git a/tests/ProblemExceptionTest.php b/tests/ProblemExceptionTest.php index 21850c9b..8c7b3924 100644 --- a/tests/ProblemExceptionTest.php +++ b/tests/ProblemExceptionTest.php @@ -20,20 +20,33 @@ public function testProblemAndOriginalResponseRemainAvailable(): void self::assertInstanceOf(Problem::class, $error->getProblem()); self::assertSame($error->getResponseBody(), $error->getProblem()); self::assertSame('Invalid amount', $error->getProblem()->detail); + self::assertSame('Invalid amount', $error->getMessage()); self::assertSame($response, $error->getResponse()); } } public function testInvalidProblemRemainsAnApiError(): void { - $body = ['type' => null]; - $response = new Response(400, $body); + foreach ([['type' => null], ['detail' => 'Token expired'], ['type' => []]] as $body) { + $response = new Response(400, $body); + try { + ResponseDecoder::decodeOrThrow($response, null, ['400' => ['type' => 'class', 'class' => Problem::class]]); + self::fail('Expected API error'); + } catch (ApiException $error) { + self::assertNull($error->getProblem()); + self::assertSame($body, $error->getResponseBody()); + } + } + } + + public function testProblemTitleIsUsedWhenDetailIsMissing(): void + { + $response = new Response(401, ['type' => 'about:blank', 'title' => 'Unauthorized']); try { - ResponseDecoder::decodeOrThrow($response, null, ['400' => ['type' => 'class', 'class' => Problem::class]]); + ResponseDecoder::decodeOrThrow($response, null, Problem::class); self::fail('Expected API error'); } catch (ApiException $error) { - self::assertNull($error->getProblem()); - self::assertSame($body, $error->getResponseBody()); + self::assertSame('Unauthorized', $error->getMessage()); } } From 119285487a9a3954738c2a8bf393abd720eae4f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matou=C5=A1=20Dzivjak?= Date: Mon, 26 Oct 2026 18:47:51 +0100 Subject: [PATCH 3/3] fix: preserve stringable values during hydration Keep existing stringable values working while rejecting malformed error fields. Place the user-facing error handling example beside basic usage. --- README.md | 34 +++++++++++++++++----------------- src/Hydrator.php | 2 +- tests/HydratorTest.php | 13 +++++++++++++ 3 files changed, 31 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 562e87cb..b8a465e0 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,23 @@ If you prefer to provide the API key directly in your code instead of using the $sumup = new \SumUp\SumUp('your-api-key-here'); ``` +### Handling errors + +API errors expose typed Problem details when available: + +```php +try { + $checkout = $sumup->checkouts()->get('your-checkout-id'); +} catch (\SumUp\Exception\ApiException $error) { + if (($problem = $error->getProblem()) !== null) { + echo $problem->type . ': ' . $problem->detail; + } +} +``` + +Use `getResponseBody()` for other error details. `getResponse()` provides the original +response, including its headers and text through `getHeaders()` and `getRawBody()`. + ### TLS Certificates The SDK ships with the latest Mozilla CA bundle to prevent `SSL certificate problem: unable to get local issuer certificate` errors on Windows and other environments that do not expose a system-wide trust store. You can override the bundled file by passing the `ca_bundle_path` configuration key: @@ -169,20 +186,3 @@ For information about the license see the [license](https://github.com/sumup/sum ## Contact Us If you have found a bug or you lack some functionality please [open an issue](https://github.com/sumup/sumup-php/issues/new). If you have other issues when integrating with SumUp's API you can send an email to [integration@sumup.com](mailto:integration@sumup.com). - -## Problem details - -API errors expose typed Problem details when available: - -```php -try { - $checkout = $sumup->checkouts()->get('your-checkout-id'); -} catch (\SumUp\Exception\ApiException $error) { - if (($problem = $error->getProblem()) !== null) { - echo $problem->type . ': ' . $problem->detail; - } -} -``` - -Use `getResponseBody()` for other error details. `getResponse()` provides the original -response, including its headers and text through `getHeaders()` and `getRawBody()`. diff --git a/src/Hydrator.php b/src/Hydrator.php index 6992d833..1f746dae 100644 --- a/src/Hydrator.php +++ b/src/Hydrator.php @@ -112,7 +112,7 @@ private static function castValue($value, ReflectionProperty $property) case 'bool': return (bool) $value; case 'string': - if (!is_scalar($value)) { + if (!is_scalar($value) && !($value instanceof \Stringable)) { throw new \InvalidArgumentException('Expected a scalar value for ' . $property->getName()); } return (string) $value; diff --git a/tests/HydratorTest.php b/tests/HydratorTest.php index faea8e64..d4b2c911 100644 --- a/tests/HydratorTest.php +++ b/tests/HydratorTest.php @@ -9,6 +9,7 @@ use SumUp\Types\MandateResponse; use SumUp\Types\MandateResponseStatus; use SumUp\Types\Receipt; +use SumUp\Types\Problem; class HydratorTest extends TestCase { @@ -79,6 +80,18 @@ public function testHydrateArrayItemsFromDocblockClassNames() $this->assertSame('https://example.test/2', $response->links[1]->href); } + public function testHydrateStringableValue(): void + { + $value = new class implements \Stringable { + public function __toString(): string + { + return 'about:blank'; + } + }; + $problem = Hydrator::hydrate(['type' => $value], Problem::class); + $this->assertSame('about:blank', $problem->type); + } + public function testHydrateInvalidBackedEnumValueThrowsValueError() { $this->expectException(\ValueError::class);