diff --git a/README.md b/README.md index 72fe5aa9..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: 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/Hydrator.php b/src/Hydrator.php index b30b9a37..1f746dae 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) && !($value instanceof \Stringable)) { + 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 5a0c5db1..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. @@ -38,7 +39,14 @@ public static function decodeOrThrow( } if (self::hasDescriptorForStatus($errorDescriptors, $statusCode)) { - $decodedErrorBody = self::decode($response, $errorDescriptors); + try { + $decodedErrorBody = self::decode($response, $errorDescriptors); + if ($decodedErrorBody instanceof Problem && !isset($decodedErrorBody->type)) { + $decodedErrorBody = $response->getBody(); + } + } catch (\TypeError | \ReflectionException | \InvalidArgumentException $exception) { + $decodedErrorBody = $response->getBody(); + } $message = self::extractErrorMessage($decodedErrorBody, self::defaultErrorMessage($statusCode)); throw new ApiException( @@ -46,7 +54,9 @@ public static function decodeOrThrow( $statusCode, $decodedErrorBody, $httpMethod, - $path + $path, + null, + $response ); } @@ -60,7 +70,9 @@ public static function decodeOrThrow( $httpMethod, $path, $response->getHeaders(), - $response->getRawBody() + $response->getRawBody(), + null, + $response ); } @@ -228,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/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); diff --git a/tests/ProblemExceptionTest.php b/tests/ProblemExceptionTest.php new file mode 100644 index 00000000..8c7b3924 --- /dev/null +++ b/tests/ProblemExceptionTest.php @@ -0,0 +1,65 @@ + '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('Invalid amount', $error->getMessage()); + self::assertSame($response, $error->getResponse()); + } + } + + public function testInvalidProblemRemainsAnApiError(): void + { + 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, Problem::class); + self::fail('Expected API error'); + } catch (ApiException $error) { + self::assertSame('Unauthorized', $error->getMessage()); + } + } + + 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()); + } + } +}