1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace OpenSearch\Exception;
6:
7: /**
8: * Extracts an error message from the response body.
9: */
10: class ErrorMessageExtractor
11: {
12: public static function extractErrorMessage(string|array|null $data): ?string
13: {
14: if (is_string($data) || is_null($data)) {
15: return $data;
16: }
17:
18: // Must be an array now.
19: if (!isset($data['error'])) {
20: // <2.0 "i just blew up" non-structured exception.
21: // $error is an array, but we don't know the format, so we reuse the response body instead
22: // added json_encode to convert into a string
23: return json_encode($data);
24: }
25:
26: // 2.0 structured exceptions
27: if (is_array($data['error']) && array_key_exists('reason', $data['error'])) {
28: // Try to use root cause first (only grabs the first root cause)
29: $info = $data['error']['root_cause'][0] ?? $data['error'];
30: $cause = $info['reason'];
31: $type = $info['type'];
32:
33: return "$type: $cause";
34: }
35:
36: // <2.0 semi-structured exceptions
37: $legacyError = $data['error'];
38: if (is_array($legacyError)) {
39: return json_encode($legacyError);
40: }
41: return $legacyError;
42: }
43: }
44: