From 3805725d46ceb0d9fb73fb662ce35edf21747441 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C5=91cze=20Bence?= Date: Tue, 18 Apr 2023 22:40:01 +0200 Subject: [PATCH] handle errors and exceptions in controllers --- src/Response/HttpResponse.php | 29 ++++++++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/src/Response/HttpResponse.php b/src/Response/HttpResponse.php index a3496d4..b66ec07 100644 --- a/src/Response/HttpResponse.php +++ b/src/Response/HttpResponse.php @@ -1,5 +1,7 @@ request = $request; $this->dbConnection = $dbConnection; $this->routeCollection = $routeCollection; @@ -81,7 +85,13 @@ class HttpResponse } $this->dbConnection->startTransaction(); - $response = call_user_func([$controller, $handler[1]]); + try { + $response = call_user_func([$controller, $handler[1]]); + } catch (Exception $exception) { + $this->dbConnection->rollback(); + $this->render500($exception); + return; + } $this->dbConnection->commit(); if ($response instanceof IContent) { @@ -114,4 +124,21 @@ class HttpResponse header('Content-Type: text/html; charset=UTF-8', true, 404); $content->render(); } + + private function render500(Exception $exception): void + { + if (empty($_ENV['DEV'])) { + $exceptionToPrint = null; + } else { + $exceptionToPrint = (string)$exception; + } + + $content = new HtmlContent($this->appConfig['error500View'], ['exceptionToPrint' => $exceptionToPrint]); + header('Content-Type: text/html; charset=UTF-8', true, 500); + $content->render(); + } + + private function exceptionsErrorHandler($severity, $message, $filename, $lineno) { + throw new ErrorException($message, 0, $severity, $filename, $lineno); + } }