Skip to content

Commit 405b1e6

Browse files
committed
Merge branch 'null-error-messages-7x' of https://github.com/mlambley/elasticsearch-php into mlambley-null-error-messages-7x
2 parents 78172a7 + 791c205 commit 405b1e6

File tree

1 file changed

+22
-8
lines changed

1 file changed

+22
-8
lines changed

src/Elasticsearch/Connections/Connection.php

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -612,7 +612,6 @@ private function buildCurlCommand(string $method, string $uri, ?string $body): s
612612
private function process4xxError(array $request, array $response, array $ignore): ?ElasticsearchException
613613
{
614614
$statusCode = $response['status'];
615-
$responseBody = $response['body'];
616615

617616
/**
618617
* @var \Exception $exception
@@ -622,12 +621,8 @@ private function process4xxError(array $request, array $response, array $ignore)
622621
if (array_search($response['status'], $ignore) !== false) {
623622
return null;
624623
}
625-
626-
// if responseBody is not string, we convert it so it can be used as Exception message
627-
if (!is_string($responseBody)) {
628-
$responseBody = json_encode($responseBody);
629-
}
630-
624+
625+
$responseBody = $this->convertBodyToString($response['body'], $statusCode, $exception);
631626
if ($statusCode === 403) {
632627
$exception = new Forbidden403Exception($responseBody, $statusCode);
633628
} elseif ($statusCode === 404) {
@@ -672,14 +667,33 @@ private function process5xxError(array $request, array $response, array $ignore)
672667
} elseif ($statusCode === 500 && strpos($responseBody, 'NoShardAvailableActionException') !== false) {
673668
$exception = new NoShardAvailableException($exception->getMessage(), $statusCode, $exception);
674669
} else {
675-
$exception = new ServerErrorResponseException($responseBody, $statusCode);
670+
$exception = new ServerErrorResponseException(
671+
$this->convertBodyToString($responseBody, $statusCode, $exception),
672+
$statusCode
673+
);
676674
}
677675

678676
$this->logRequestFail($request, $response, $exception);
679677

680678
throw $exception;
681679
}
682680

681+
private function convertBodyToString($body, int $statusCode, ElasticsearchException $exception) : string
682+
{
683+
if (empty($body)) {
684+
return sprintf(
685+
"Unknown %d error from Elasticsearch %s",
686+
$statusCode,
687+
$exception->getMessage()
688+
);
689+
}
690+
// if body is not string, we convert it so it can be used as Exception message
691+
if (!is_string($body)) {
692+
return json_encode($body);
693+
}
694+
return $body;
695+
}
696+
683697
private function tryDeserialize400Error(array $response): ElasticsearchException
684698
{
685699
return $this->tryDeserializeError($response, BadRequest400Exception::class);

0 commit comments

Comments
 (0)