From 144a5415da7f0fdbbd6f84b0918c7daae4dfbf4a Mon Sep 17 00:00:00 2001 From: Alejandro Celaya Date: Sat, 29 Dec 2018 13:50:42 +0100 Subject: [PATCH] Handled connection exceptions in Health action --- module/Rest/src/Action/HealthAction.php | 9 ++++++-- module/Rest/test/Action/HealthActionTest.php | 23 ++++++++++++++++++++ 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/module/Rest/src/Action/HealthAction.php b/module/Rest/src/Action/HealthAction.php index d062d5b2..2cb08030 100644 --- a/module/Rest/src/Action/HealthAction.php +++ b/module/Rest/src/Action/HealthAction.php @@ -8,6 +8,7 @@ use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Log\LoggerInterface; use Shlinkio\Shlink\Core\Options\AppOptions; +use Throwable; use Zend\Diactoros\Response\JsonResponse; class HealthAction extends AbstractRestAction @@ -38,9 +39,13 @@ class HealthAction extends AbstractRestAction */ public function handle(ServerRequestInterface $request): ResponseInterface { - $connected = $this->conn->ping(); - $statusCode = $connected ? self::STATUS_OK : self::STATUS_SERVICE_UNAVAILABLE; + try { + $connected = $this->conn->ping(); + } catch (Throwable $e) { + $connected = false; + } + $statusCode = $connected ? self::STATUS_OK : self::STATUS_SERVICE_UNAVAILABLE; return new JsonResponse([ 'status' => $connected ? self::PASS_STATUS : self::FAIL_STATUS, 'version' => $this->options->getVersion(), diff --git a/module/Rest/test/Action/HealthActionTest.php b/module/Rest/test/Action/HealthActionTest.php index 93371876..efca74b4 100644 --- a/module/Rest/test/Action/HealthActionTest.php +++ b/module/Rest/test/Action/HealthActionTest.php @@ -4,6 +4,7 @@ declare(strict_types=1); namespace ShlinkioTest\Shlink\Rest\Action; use Doctrine\DBAL\Connection; +use Exception; use PHPUnit\Framework\TestCase; use Prophecy\Prophecy\ObjectProphecy; use Shlinkio\Shlink\Core\Options\AppOptions; @@ -67,4 +68,26 @@ class HealthActionTest extends TestCase $this->assertEquals('application/health+json', $resp->getHeaderLine('Content-type')); $ping->shouldHaveBeenCalledOnce(); } + + /** + * @test + */ + public function failResponseIsReturnedWhenConnectionThrowsException() + { + $ping = $this->conn->ping()->willThrow(Exception::class); + + /** @var JsonResponse $resp */ + $resp = $this->action->handle(new ServerRequest()); + $payload = $resp->getPayload(); + + $this->assertEquals(503, $resp->getStatusCode()); + $this->assertEquals('fail', $payload['status']); + $this->assertEquals('1.2.3', $payload['version']); + $this->assertEquals([ + 'about' => 'https://shlink.io', + 'project' => 'https://github.com/shlinkio/shlink', + ], $payload['links']); + $this->assertEquals('application/health+json', $resp->getHeaderLine('Content-type')); + $ping->shouldHaveBeenCalledOnce(); + } }