diff --git a/src/Elasticsearch/Connections/Connection.php b/src/Elasticsearch/Connections/Connection.php index 5e94d0ef9..413e00e39 100644 --- a/src/Elasticsearch/Connections/Connection.php +++ b/src/Elasticsearch/Connections/Connection.php @@ -37,6 +37,7 @@ use Elasticsearch\Common\Exceptions\TransportException; use Elasticsearch\Serializers\SerializerInterface; use Elasticsearch\Transport; +use Exception; use GuzzleHttp\Ring\Core; use GuzzleHttp\Ring\Exception\ConnectException; use GuzzleHttp\Ring\Exception\RingException; @@ -612,7 +613,6 @@ private function buildCurlCommand(string $method, string $uri, ?string $body): s private function process4xxError(array $request, array $response, array $ignore): ?ElasticsearchException { $statusCode = $response['status']; - $responseBody = $response['body']; /** * @var \Exception $exception @@ -622,12 +622,8 @@ private function process4xxError(array $request, array $response, array $ignore) if (array_search($response['status'], $ignore) !== false) { return null; } - - // if responseBody is not string, we convert it so it can be used as Exception message - if (!is_string($responseBody)) { - $responseBody = json_encode($responseBody); - } - + + $responseBody = $this->convertBodyToString($response['body'], $statusCode, $exception); if ($statusCode === 403) { $exception = new Forbidden403Exception($responseBody, $statusCode); } elseif ($statusCode === 404) { @@ -672,7 +668,10 @@ private function process5xxError(array $request, array $response, array $ignore) } elseif ($statusCode === 500 && strpos($responseBody, 'NoShardAvailableActionException') !== false) { $exception = new NoShardAvailableException($exception->getMessage(), $statusCode, $exception); } else { - $exception = new ServerErrorResponseException($responseBody, $statusCode); + $exception = new ServerErrorResponseException( + $this->convertBodyToString($responseBody, $statusCode, $exception), + $statusCode + ); } $this->logRequestFail($request, $response, $exception); @@ -680,6 +679,22 @@ private function process5xxError(array $request, array $response, array $ignore) throw $exception; } + private function convertBodyToString($body, int $statusCode, Exception $exception) : string + { + if (empty($body)) { + return sprintf( + "Unknown %d error from Elasticsearch %s", + $statusCode, + $exception->getMessage() + ); + } + // if body is not string, we convert it so it can be used as Exception message + if (!is_string($body)) { + return json_encode($body); + } + return $body; + } + private function tryDeserialize400Error(array $response): ElasticsearchException { return $this->tryDeserializeError($response, BadRequest400Exception::class);