3737use Elasticsearch \Common \Exceptions \TransportException ;
3838use Elasticsearch \Serializers \SerializerInterface ;
3939use Elasticsearch \Transport ;
40+ use Exception ;
4041use GuzzleHttp \Ring \Core ;
4142use GuzzleHttp \Ring \Exception \ConnectException ;
4243use GuzzleHttp \Ring \Exception \RingException ;
@@ -612,7 +613,6 @@ private function buildCurlCommand(string $method, string $uri, ?string $body): s
612613 private function process4xxError (array $ request , array $ response , array $ ignore ): ?ElasticsearchException
613614 {
614615 $ statusCode = $ response ['status ' ];
615- $ responseBody = $ response ['body ' ];
616616
617617 /**
618618 * @var \Exception $exception
@@ -622,12 +622,8 @@ private function process4xxError(array $request, array $response, array $ignore)
622622 if (array_search ($ response ['status ' ], $ ignore ) !== false ) {
623623 return null ;
624624 }
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-
625+
626+ $ responseBody = $ this ->convertBodyToString ($ response ['body ' ], $ statusCode , $ exception );
631627 if ($ statusCode === 403 ) {
632628 $ exception = new Forbidden403Exception ($ responseBody , $ statusCode );
633629 } elseif ($ statusCode === 404 ) {
@@ -672,14 +668,33 @@ private function process5xxError(array $request, array $response, array $ignore)
672668 } elseif ($ statusCode === 500 && strpos ($ responseBody , 'NoShardAvailableActionException ' ) !== false ) {
673669 $ exception = new NoShardAvailableException ($ exception ->getMessage (), $ statusCode , $ exception );
674670 } else {
675- $ exception = new ServerErrorResponseException ($ responseBody , $ statusCode );
671+ $ exception = new ServerErrorResponseException (
672+ $ this ->convertBodyToString ($ responseBody , $ statusCode , $ exception ),
673+ $ statusCode
674+ );
676675 }
677676
678677 $ this ->logRequestFail ($ request , $ response , $ exception );
679678
680679 throw $ exception ;
681680 }
682681
682+ private function convertBodyToString ($ body , int $ statusCode , Exception $ exception ) : string
683+ {
684+ if (empty ($ body )) {
685+ return sprintf (
686+ "Unknown %d error from Elasticsearch %s " ,
687+ $ statusCode ,
688+ $ exception ->getMessage ()
689+ );
690+ }
691+ // if body is not string, we convert it so it can be used as Exception message
692+ if (!is_string ($ body )) {
693+ return json_encode ($ body );
694+ }
695+ return $ body ;
696+ }
697+
683698 private function tryDeserialize400Error (array $ response ): ElasticsearchException
684699 {
685700 return $ this ->tryDeserializeError ($ response , BadRequest400Exception::class);
0 commit comments