1: <?php
2:
3: declare(strict_types=1);
4:
5: namespace OpenSearch\Exception;
6:
7: /**
8: * Factory for creating HTTP exceptions.
9: */
10: class HttpExceptionFactory
11: {
12: public static function create(
13: int $statusCode,
14: string|array|null $data,
15: array $headers = [],
16: int $code = 0,
17: ?\Throwable $previous = null
18: ): HttpExceptionInterface {
19:
20: $errorMessage = ErrorMessageExtractor::extractErrorMessage($data);
21:
22: return match ($statusCode) {
23: 400 => self::createBadRequestException($errorMessage, $previous, $code, $headers),
24: 401 => new UnauthorizedHttpException($errorMessage, $headers, $code, $previous),
25: 403 => new ForbiddenHttpException($errorMessage, $headers, $code, $previous),
26: 404 => new NotFoundHttpException($errorMessage, $headers, $code, $previous),
27: 406 => new NotAcceptableHttpException($errorMessage, $headers, $code, $previous),
28: 409 => new ConflictHttpException($errorMessage, $headers, $code, $previous),
29: 429 => new TooManyRequestsHttpException($errorMessage, $headers, $code, $previous),
30: 500 => self::createInternalServerErrorException($errorMessage, $previous, $code, $headers),
31: 503 => new ServiceUnavailableHttpException($errorMessage, $headers, $code, $previous),
32: default => new HttpException($statusCode, $errorMessage, $headers, $code, $previous),
33: };
34: }
35:
36: private static function createBadRequestException(
37: string $message = '',
38: ?\Throwable $previous = null,
39: int $code = 0,
40: array $headers = []
41: ): HttpExceptionInterface {
42: if (str_contains($message, 'script_lang not supported')) {
43: return new ScriptLangNotSupportedException($message);
44: }
45: return new BadRequestHttpException($message, $headers, $code, $previous);
46: }
47:
48: /**
49: * Create an InternalServerErrorHttpException from the given parameters.
50: */
51: private static function createInternalServerErrorException(
52: string $message = '',
53: ?\Throwable $previous = null,
54: int $code = 0,
55: array $headers = []
56: ): HttpExceptionInterface {
57: if (str_contains($message, "RoutingMissingException")) {
58: return new RoutingMissingException($message);
59: }
60: if (preg_match('/ActionRequestValidationException.+ no documents to get/', $message) === 1) {
61: return new NoDocumentsToGetException($message);
62: }
63: if (str_contains($message, 'NoShardAvailableActionException')) {
64: return new NoShardAvailableException($message);
65: }
66: return new InternalServerErrorHttpException($message, $headers, $code, $previous);
67: }
68:
69: }
70: