From a2609a97357053ddbabbe1a7301f4c35a2cf6453 Mon Sep 17 00:00:00 2001 From: Anthony daCosta Date: Thu, 18 Dec 2025 21:36:47 +0000 Subject: [PATCH] fix(api_call): Handle invalid server response When server response is invalid json still should attempt to respond with proper error code. --- src/ApiCall.php | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/ApiCall.php b/src/ApiCall.php index a0c44459..33ff57c8 100644 --- a/src/ApiCall.php +++ b/src/ApiCall.php @@ -6,10 +6,11 @@ use Http\Client\Common\HttpMethodsClient; use Http\Client\Exception as HttpClientException; use Http\Client\Exception\HttpException; +use Http\Discovery\Psr17FactoryDiscovery; +use JsonException; use Psr\Http\Client\ClientInterface; use Psr\Http\Message\StreamInterface; use Psr\Log\LoggerInterface; -use Http\Discovery\Psr17FactoryDiscovery; use Typesense\Exceptions\HTTPStatus0Error; use Typesense\Exceptions\ObjectAlreadyExists; use Typesense\Exceptions\ObjectNotFound; @@ -255,16 +256,21 @@ private function makeRequest(string $method, string $endPoint, bool $asJson, arr $this->setNodeHealthCheck($node, true); } + $responseContents = $response->getBody() + ->getContents(); + if (!(200 <= $statusCode && $statusCode < 300)) { - $errorMessage = json_decode($response->getBody() - ->getContents(), true, 512, JSON_THROW_ON_ERROR)['message'] ?? 'API error.'; + try { + $responseContents = json_decode($responseContents, true, 512, JSON_THROW_ON_ERROR); + $errorMessage = $responseContents['message'] ?? 'API error.'; + } catch (JsonException $exception) { + $errorMessage = $responseContents ?? 'API error.'; + } throw $this->getException($statusCode) ->setMessage($errorMessage); } - return $asJson ? json_decode($response->getBody() - ->getContents(), true, 512, JSON_THROW_ON_ERROR) : $response->getBody() - ->getContents(); + return $asJson ? json_decode($responseContents, true, 512, JSON_THROW_ON_ERROR) : $responseContents; } catch (HttpException $exception) { $statusCode = $exception->getResponse()->getStatusCode();