diff --git a/src/Controller/AbstractController.php b/src/Controller/AbstractController.php index 66ee267..7de2e8a 100644 --- a/src/Controller/AbstractController.php +++ b/src/Controller/AbstractController.php @@ -2,11 +2,31 @@ namespace AlexMorbo\React\Trassir\Controller; +use HttpSoft\Response\JsonResponse; +use Psr\Http\Message\ResponseInterface; +use Psr\Log\LoggerInterface; +use React\Promise\PromiseInterface; +use Throwable; use Tnapf\Router\Router; +use function React\Async\await; + abstract class AbstractController { + protected ?LoggerInterface $logger = null; + public function addRoutes(Router $router): void { } + + protected function awaitResponse(PromiseInterface $promise): ResponseInterface + { + try { + return await($promise); + } catch (Throwable $e) { + $this->logger->error('Async error', ['message' => $e->getMessage()]); + + return new JsonResponse(['status' => 'error', 'error' => $e->getMessage()], 404); + } + } } \ No newline at end of file diff --git a/src/Controller/InstanceController.php b/src/Controller/InstanceController.php index 51d6ee7..de362d1 100644 --- a/src/Controller/InstanceController.php +++ b/src/Controller/InstanceController.php @@ -3,7 +3,6 @@ namespace AlexMorbo\React\Trassir\Controller; use AlexMorbo\React\Trassir\Dto\Instance; -use AlexMorbo\React\Trassir\Log; use AlexMorbo\React\Trassir\Traits\DBTrait; use AlexMorbo\React\Trassir\TrassirHelper; use AlexMorbo\Trassir\TrassirException; @@ -19,7 +18,6 @@ use Tnapf\Router\Router; use Tnapf\Router\Routing\RouteRunner; -use function React\Async\await; use function React\Promise\all; use function React\Promise\resolve; @@ -28,7 +26,7 @@ class InstanceController extends AbstractController use DBTrait; public function __construct( - private LoggerInterface $logger, + protected ?LoggerInterface $logger, DatabaseInterface $db, protected TrassirHelper $trassirHelper ) { @@ -132,7 +130,7 @@ function (Instance $instance) use ($instanceData) { } ); - return await($promise); + return $this->awaitResponse($promise); } public function getInstance( @@ -161,7 +159,7 @@ function (Instance $instance) use ($result) { } ); - return await($promise); + return $this->awaitResponse($promise); } public function addInstance(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface @@ -237,7 +235,7 @@ function ($error) { } ); - return await($promise); + return $this->awaitResponse($promise); } public function deleteInstance( @@ -271,7 +269,7 @@ function ($error) { } ); - return await($promise); + return $this->awaitResponse($promise); } public function getChannelScreenshot( @@ -304,7 +302,7 @@ function ($screenshot) use ($response) { } ); - return await($promise); + return $this->awaitResponse($promise); } public function getChannelVideo( @@ -364,7 +362,7 @@ function (Exception $e) { } ); - return await($promise); + return $this->awaitResponse($promise); }