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
15 changes: 14 additions & 1 deletion src/ApiCall.php
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,20 @@ private function makeRequest(string $method, string $endPoint, bool $asJson, arr
->setMessage($errorMessage);
}

return $asJson ? json_decode($responseContents, true, 512, JSON_THROW_ON_ERROR) : $responseContents;
if (!$asJson) {
return $responseContents;
}

try {
return json_decode($responseContents, true, 512, JSON_THROW_ON_ERROR);
} catch (JsonException $exception) {
throw new TypesenseClientError(
'HTTP ' . $response->getStatusCode() . ' response is not valid JSON: '
. substr($responseContents, 0, 200),
0,
$exception
);
}
} catch (HttpException $exception) {
$statusCode = $exception->getResponse()->getStatusCode();

Expand Down
38 changes: 37 additions & 1 deletion tests/Feature/ApiCallRetryTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,12 @@
use Typesense\Exceptions\RequestMalformed;
use Http\Client\Exception\HttpException;
use Http\Client\Exception\TransferException;
use JsonException;
use Psr\Http\Client\ClientInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\StreamInterface;
use Psr\Http\Message\RequestInterface;
use Typesense\Exceptions\TypesenseClientError;

class ApiCallRetryTest extends TestCase
{
Expand Down Expand Up @@ -464,4 +466,38 @@ public function testDoesNotSleepOnFinalRetryAttempt(): void
"Execution was too fast ({$actualDuration}s), suggesting sleep intervals were skipped"
);
}
}

public function testThrowsTypesenseClientErrorWhenSuccessResponseContainsInvalidJson(): void
{
$httpClient = $this->createMock(ClientInterface::class);
$httpClient->method('sendRequest')
->willReturnCallback(function () {
$response = $this->createMock(ResponseInterface::class);
$response->method('getStatusCode')->willReturn(200);
$stream = $this->createMock(StreamInterface::class);
$stream->method('getContents')->willReturn('{invalid json');
$response->method('getBody')->willReturn($stream);
return $response;
});

$config = new Configuration([
'api_key' => 'test-key',
'nodes' => [
['host' => 'node1', 'port' => 8108, 'protocol' => 'http']
],
'num_retries' => 0,
'client' => $httpClient
]);

$apiCall = new ApiCall($config);

try {
$apiCall->get('/test', []);
$this->fail('Expected TypesenseClientError to be thrown');
} catch (TypesenseClientError $exception) {
$this->assertStringContainsString('HTTP 200 response is not valid JSON:', $exception->getMessage());
$this->assertStringContainsString('{invalid json', $exception->getMessage());
$this->assertInstanceOf(JsonException::class, $exception->getPrevious());
}
}
}