handle errors and exceptions in controllers
This commit is contained in:
parent
51801d4228
commit
3805725d46
@ -1,5 +1,7 @@
|
|||||||
<?php namespace SokoWeb\Response;
|
<?php namespace SokoWeb\Response;
|
||||||
|
|
||||||
|
use ErrorException;
|
||||||
|
use Exception;
|
||||||
use SokoWeb\Interfaces\Response\IRedirect;
|
use SokoWeb\Interfaces\Response\IRedirect;
|
||||||
use SokoWeb\Interfaces\Response\IContent;
|
use SokoWeb\Interfaces\Response\IContent;
|
||||||
use SokoWeb\Interfaces\Authentication\IAuthenticationRequired;
|
use SokoWeb\Interfaces\Authentication\IAuthenticationRequired;
|
||||||
@ -35,6 +37,8 @@ class HttpResponse
|
|||||||
string $requestMethod,
|
string $requestMethod,
|
||||||
string $requestUrl
|
string $requestUrl
|
||||||
) {
|
) {
|
||||||
|
set_error_handler([$this, 'exceptionsErrorHandler']);
|
||||||
|
|
||||||
$this->request = $request;
|
$this->request = $request;
|
||||||
$this->dbConnection = $dbConnection;
|
$this->dbConnection = $dbConnection;
|
||||||
$this->routeCollection = $routeCollection;
|
$this->routeCollection = $routeCollection;
|
||||||
@ -81,7 +85,13 @@ class HttpResponse
|
|||||||
}
|
}
|
||||||
|
|
||||||
$this->dbConnection->startTransaction();
|
$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();
|
$this->dbConnection->commit();
|
||||||
|
|
||||||
if ($response instanceof IContent) {
|
if ($response instanceof IContent) {
|
||||||
@ -114,4 +124,21 @@ class HttpResponse
|
|||||||
header('Content-Type: text/html; charset=UTF-8', true, 404);
|
header('Content-Type: text/html; charset=UTF-8', true, 404);
|
||||||
$content->render();
|
$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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user