Add constructor, setExceptionHandler, call HtmlErrorRenderer

This commit is contained in:
billz 2023-12-27 05:37:54 +00:00
parent 41bba09f42
commit 405ae0bf17

View file

@ -3,7 +3,7 @@
/**
* Exception handler class
*
* @description
* @description A simple exception handler for RaspAP
* @author Bill Zimmerman <billzimmerman@gmail.com>
* @license https://github.com/raspap/raspap-webgui/blob/master/LICENSE
* @see
@ -13,45 +13,57 @@ declare(strict_types=1);
namespace RaspAP\Exceptions;
class ExceptionHandler {
public static function handleException($exception) {
// Log the exception to a file or a service
$errorMessage = '[' . date('Y-m-d H:i:s') . '] ' . $exception->getMessage() . ' in ' . $exception->getFile() . ' on line ' . $exception->getLine() . PHP_EOL;
use RaspAP\Exceptions\HtmlErrorRenderer;
class ExceptionHandler
{
public function __construct()
{
$this->setExceptionHandler();
$this->setShutdownHandler();
}
public static function handleException($exception)
{
$errorMessage = (
'[' . date('Y-m-d H:i:s') . '] ' .
$exception->getMessage() . ' in ' .
$exception->getFile() . ' on line ' .
$exception->getLine() . PHP_EOL
);
// Log the exception
error_log($errorMessage, 3, 'error.log');
echo '<h3>An error occured</h3>';
echo '<p>'.$errorMessage.'</p>';
//header('Location: error_page.php');
$renderer = new HtmlErrorRenderer();
$renderer->render($exception);
}
public static function handleFatalError() {
public static function handleShutdown()
{
$error = error_get_last();
if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
// Log the fatal error
$errorMessage = '[' . date('Y-m-d H:i:s') . '] ' . $error['message'] . ' in ' . $error['file'] . ' on line ' . $error['line'] . PHP_EOL;
$errorMessage = (
'[' . date('Y-m-d H:i:s') . '] ' .
$error['message'] . ' in ' .
$error['file'] . ' on line ' .
$error['line'] . PHP_EOL
);
error_log($errorMessage, 3, 'error.log');
// Return HTTP 500 status header
//http_response_code(500);
echo '<h3>A Fatal error occured</h3>';
echo '<p>'.$errorMessage.'</p>';
exit;
$renderer = new HtmlErrorRenderer();
$renderer->render($exception);
}
}
public static function handleShutdown() {
$error = error_get_last();
if ($error !== null && in_array($error['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
$errorMessage = '[' . date('Y-m-d H:i:s') . '] ' . $error['message'] . ' in ' . $error['file'] . ' on line ' . $error['line'] . PHP_EOL;
error_log($errorMessage, 3, 'error.log');
protected function setExceptionHandler()
{
set_exception_handler(array($this, 'handleException'));
}
echo '<h3>Executing shutdown</h3>';
echo '<p>'.$errorMessage.'</p>';
// header('Location: error_page.php');
}
protected function setShutdownHandler()
{
register_shutdown_function(array($this, 'handleShutdown'));
}
}