Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
21 changes: 20 additions & 1 deletion src/Exception/ApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand All @@ -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
Expand All @@ -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;
}
}
5 changes: 3 additions & 2 deletions src/Exception/UnexpectedApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 1 addition & 1 deletion src/HttpClient/GuzzleClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/Hydrator.php
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
20 changes: 16 additions & 4 deletions src/ResponseDecoder.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -38,15 +39,24 @@ 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(
$message,
$statusCode,
$decodedErrorBody,
$httpMethod,
$path
$path,
null,
$response
);
}

Expand All @@ -60,7 +70,9 @@ public static function decodeOrThrow(
$httpMethod,
$path,
$response->getHeaders(),
$response->getRawBody()
$response->getRawBody(),
null,
$response
);
}

Expand Down Expand Up @@ -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;
Expand Down
13 changes: 13 additions & 0 deletions tests/HydratorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
use SumUp\Types\MandateResponse;
use SumUp\Types\MandateResponseStatus;
use SumUp\Types\Receipt;
use SumUp\Types\Problem;

class HydratorTest extends TestCase
{
Expand Down Expand Up @@ -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);
Expand Down
65 changes: 65 additions & 0 deletions tests/ProblemExceptionTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

use PHPUnit\Framework\TestCase;
use SumUp\Exception\ApiException;
use SumUp\Exception\UnexpectedApiException;
use SumUp\HttpClient\Response;
use SumUp\ResponseDecoder;
use SumUp\Types\Problem;

final class ProblemExceptionTest extends TestCase
{
public function testProblemAndOriginalResponseRemainAvailable(): void
{
$body = ['type' => '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());
}
}
}
Loading