Skip to content

Commit

Permalink
feat: propagate clickhouse error code to ServerError (#266)
Browse files Browse the repository at this point in the history
  • Loading branch information
simPod authored Oct 9, 2024
1 parent cdba36f commit bff3805
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
9 changes: 8 additions & 1 deletion src/Exception/ServerError.php
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);
}
}
30 changes: 30 additions & 0 deletions tests/Exception/ServerErrorTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

declare(strict_types=1);

namespace SimPod\ClickHouseClient\Tests\Exception;

use Nyholm\Psr7\Factory\Psr17Factory;
use PHPUnit\Framework\Attributes\CoversClass;
use SimPod\ClickHouseClient\Exception\ServerError;
use SimPod\ClickHouseClient\Tests\TestCaseBase;

#[CoversClass(ServerError::class)]
final class ServerErrorTest extends TestCaseBase
{
public function testParseCode(): void
{
$psr17Factory = new Psr17Factory();
$response = $psr17Factory->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());
}
}

0 comments on commit bff3805

Please sign in to comment.