Skip to content

Commit e113f90

Browse files
authored
Merge pull request #111 from vortextangent/master
fix(api_call): Handle invalid server response
2 parents a35736e + a2609a9 commit e113f90

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

src/ApiCall.php

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66
use Http\Client\Common\HttpMethodsClient;
77
use Http\Client\Exception as HttpClientException;
88
use Http\Client\Exception\HttpException;
9+
use Http\Discovery\Psr17FactoryDiscovery;
10+
use JsonException;
911
use Psr\Http\Client\ClientInterface;
1012
use Psr\Http\Message\StreamInterface;
1113
use Psr\Log\LoggerInterface;
12-
use Http\Discovery\Psr17FactoryDiscovery;
1314
use Typesense\Exceptions\HTTPStatus0Error;
1415
use Typesense\Exceptions\ObjectAlreadyExists;
1516
use Typesense\Exceptions\ObjectNotFound;
@@ -255,16 +256,21 @@ private function makeRequest(string $method, string $endPoint, bool $asJson, arr
255256
$this->setNodeHealthCheck($node, true);
256257
}
257258

259+
$responseContents = $response->getBody()
260+
->getContents();
261+
258262
if (!(200 <= $statusCode && $statusCode < 300)) {
259-
$errorMessage = json_decode($response->getBody()
260-
->getContents(), true, 512, JSON_THROW_ON_ERROR)['message'] ?? 'API error.';
263+
try {
264+
$responseContents = json_decode($responseContents, true, 512, JSON_THROW_ON_ERROR);
265+
$errorMessage = $responseContents['message'] ?? 'API error.';
266+
} catch (JsonException $exception) {
267+
$errorMessage = $responseContents ?? 'API error.';
268+
}
261269
throw $this->getException($statusCode)
262270
->setMessage($errorMessage);
263271
}
264272

265-
return $asJson ? json_decode($response->getBody()
266-
->getContents(), true, 512, JSON_THROW_ON_ERROR) : $response->getBody()
267-
->getContents();
273+
return $asJson ? json_decode($responseContents, true, 512, JSON_THROW_ON_ERROR) : $responseContents;
268274
} catch (HttpException $exception) {
269275
$statusCode = $exception->getResponse()->getStatusCode();
270276

0 commit comments

Comments
 (0)