From 791c205bde8bdf5de5bff9228cc709fcf1eb1d77 Mon Sep 17 00:00:00 2001 From: Mark Lambley Date: Thu, 20 Aug 2020 21:16:04 +1000 Subject: [PATCH] Show generic error messages when server returns no response --- src/Elasticsearch/Connections/Connection.php | 30 ++++++++++++++------ 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/src/Elasticsearch/Connections/Connection.php b/src/Elasticsearch/Connections/Connection.php index 661c9f6df..94cd09681 100644 --- a/src/Elasticsearch/Connections/Connection.php +++ b/src/Elasticsearch/Connections/Connection.php @@ -607,7 +607,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 @@ -617,12 +616,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) { @@ -667,7 +662,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); @@ -675,6 +673,22 @@ private function process5xxError(array $request, array $response, array $ignore) throw $exception; } + private function convertBodyToString($body, int $statusCode, ElasticsearchException $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);