Skip to content

Commit 791c205

Browse files
committed
Show generic error messages when server returns no response
1 parent 156bf4c commit 791c205

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
@@ -607,7 +607,6 @@ private function buildCurlCommand(string $method, string $uri, ?string $body): s
607607
private function process4xxError(array $request, array $response, array $ignore): ?ElasticsearchException
608608
{
609609
$statusCode = $response['status'];
610-
$responseBody = $response['body'];
611610

612611
/**
613612
* @var \Exception $exception
@@ -617,12 +616,8 @@ private function process4xxError(array $request, array $response, array $ignore)
617616
if (array_search($response['status'], $ignore) !== false) {
618617
return null;
619618
}
620-
621-
// if responseBody is not string, we convert it so it can be used as Exception message
622-
if (!is_string($responseBody)) {
623-
$responseBody = json_encode($responseBody);
624-
}
625-
619+
620+
$responseBody = $this->convertBodyToString($response['body'], $statusCode, $exception);
626621
if ($statusCode === 403) {
627622
$exception = new Forbidden403Exception($responseBody, $statusCode);
628623
} elseif ($statusCode === 404) {
@@ -667,14 +662,33 @@ private function process5xxError(array $request, array $response, array $ignore)
667662
} elseif ($statusCode === 500 && strpos($responseBody, 'NoShardAvailableActionException') !== false) {
668663
$exception = new NoShardAvailableException($exception->getMessage(), $statusCode, $exception);
669664
} else {
670-
$exception = new ServerErrorResponseException($responseBody, $statusCode);
665+
$exception = new ServerErrorResponseException(
666+
$this->convertBodyToString($responseBody, $statusCode, $exception),
667+
$statusCode
668+
);
671669
}
672670

673671
$this->logRequestFail($request, $response, $exception);
674672

675673
throw $exception;
676674
}
677675

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

0 commit comments

Comments
 (0)