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
16 changes: 15 additions & 1 deletion lib/Core/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,22 @@ private function handleErrors(Response $response)
return null;
}

// Normalize string errors into standard error object format
if (is_string($json->error)) {
$json->error = (object)[
'code' => $status_code,
'message' => $json->error
];
// Create a new response with normalized error structure
$response = new Response(
$status_code,
$response->getHeaders(),
json_encode($json)
);
}

$error = $json->error;
$exception_class = (string) ApiException::getError($status_code, $error->type);
$exception_class = (string) ApiException::getError($status_code, $error->type ?? null);
$exception_class = 'GoCardlessPro\\Core\\Exception\\' . $exception_class;

$api_response = new ApiResponse($response);
Expand Down
2 changes: 2 additions & 0 deletions lib/Core/Exception/ApiException.php
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ public function __construct($api_response)
public static function getError($status_code, $error_type)
{
switch ($status_code) {
case 400:
return 'InvalidApiUsageException';
case 401:
return 'AuthenticationException';
case 403:
Expand Down
22 changes: 22 additions & 0 deletions tests/Core/ApiClientTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -233,4 +233,26 @@ public function testGoCardlessErrorResponse()
throw $e;
}
}

public function testStringErrorResponse()
{
$fixture = $this->loadFixture('string_error');
$this->expectException('\GoCardlessPro\Core\Exception\ApiException');
$this->expectExceptionMessage('Something went wrong');

$this->mock->append(new \GuzzleHttp\Psr7\Response(400, ['Content-Type' => 'application/json'], $fixture));

try {
$this->api_client->get('/some_endpoint');
} catch (\GoCardlessPro\Core\Exception\ApiException $e) {
$this->assertEquals($e->getApiResponse()->status_code, '400');
$this->assertEquals($e->getApiResponse()->headers, ['Content-Type' => ['application/json']]);
$this->assertEquals($e->getMessage(), 'Something went wrong');

// Verify that methods return appropriate values for string errors
$this->assertEquals(array(), $e->getErrors());

throw $e;
}
}
}
3 changes: 3 additions & 0 deletions tests/fixtures/string_error.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
{
"error": "Something went wrong"
}