From bff3805c050ec3d563eea056ccc71bdbfd0b5d6a Mon Sep 17 00:00:00 2001 From: Simon Podlipsky Date: Wed, 9 Oct 2024 14:45:18 +0200 Subject: [PATCH] feat: propagate clickhouse error code to ServerError (#266) --- src/Exception/ServerError.php | 9 ++++++++- tests/Exception/ServerErrorTest.php | 30 +++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+), 1 deletion(-) create mode 100644 tests/Exception/ServerErrorTest.php diff --git a/src/Exception/ServerError.php b/src/Exception/ServerError.php index 9ea6576..952a96f 100644 --- a/src/Exception/ServerError.php +++ b/src/Exception/ServerError.php @@ -7,10 +7,17 @@ use Exception; use Psr\Http\Message\ResponseInterface; +use function preg_match; + final class ServerError extends Exception { public static function fromResponse(ResponseInterface $response): self { - return new self($response->getBody()->__toString()); + $bodyContent = $response->getBody()->__toString(); + + return new self( + $bodyContent, + code: preg_match('~^Code: (\\d+). DB::Exception:~', $bodyContent, $matches) === 1 ? (int) $matches[1] : 0, + ); } } diff --git a/tests/Exception/ServerErrorTest.php b/tests/Exception/ServerErrorTest.php new file mode 100644 index 0000000..b70ac68 --- /dev/null +++ b/tests/Exception/ServerErrorTest.php @@ -0,0 +1,30 @@ +createResponse(501) + ->withBody( + $psr17Factory->createStream( + // phpcs:ignore SlevomatCodingStandard.Files.LineLength.LineTooLong + "Code: 48. DB::Exception: Table engine Distributed doesn't support mutations. (NOT_IMPLEMENTED) (version 24.3.12.75 (official build))", + ), + ); + + $serverError = ServerError::fromResponse($response); + + self::assertSame(48, $serverError->getCode()); + } +}