37
37
use Elasticsearch \Common \Exceptions \TransportException ;
38
38
use Elasticsearch \Serializers \SerializerInterface ;
39
39
use Elasticsearch \Transport ;
40
+ use Exception ;
40
41
use GuzzleHttp \Ring \Core ;
41
42
use GuzzleHttp \Ring \Exception \ConnectException ;
42
43
use GuzzleHttp \Ring \Exception \RingException ;
@@ -612,7 +613,6 @@ private function buildCurlCommand(string $method, string $uri, ?string $body): s
612
613
private function process4xxError (array $ request , array $ response , array $ ignore ): ?ElasticsearchException
613
614
{
614
615
$ statusCode = $ response ['status ' ];
615
- $ responseBody = $ response ['body ' ];
616
616
617
617
/**
618
618
* @var \Exception $exception
@@ -622,12 +622,8 @@ private function process4xxError(array $request, array $response, array $ignore)
622
622
if (array_search ($ response ['status ' ], $ ignore ) !== false ) {
623
623
return null ;
624
624
}
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 );
631
627
if ($ statusCode === 403 ) {
632
628
$ exception = new Forbidden403Exception ($ responseBody , $ statusCode );
633
629
} elseif ($ statusCode === 404 ) {
@@ -672,14 +668,33 @@ private function process5xxError(array $request, array $response, array $ignore)
672
668
} elseif ($ statusCode === 500 && strpos ($ responseBody , 'NoShardAvailableActionException ' ) !== false ) {
673
669
$ exception = new NoShardAvailableException ($ exception ->getMessage (), $ statusCode , $ exception );
674
670
} else {
675
- $ exception = new ServerErrorResponseException ($ responseBody , $ statusCode );
671
+ $ exception = new ServerErrorResponseException (
672
+ $ this ->convertBodyToString ($ responseBody , $ statusCode , $ exception ),
673
+ $ statusCode
674
+ );
676
675
}
677
676
678
677
$ this ->logRequestFail ($ request , $ response , $ exception );
679
678
680
679
throw $ exception ;
681
680
}
682
681
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
+
683
698
private function tryDeserialize400Error (array $ response ): ElasticsearchException
684
699
{
685
700
return $ this ->tryDeserializeError ($ response , BadRequest400Exception::class);
0 commit comments