<?php
namespace core\libs;
use Error;
use Throwable;
class ErrorHandler
{
private $head;
private $file;
private $line;
public function __construct()
{
set_error_handler([$this, 'errorHandler']);
ob_start();
set_exception_handler([$this, 'exceptionHandler']);
}
public function errorHandler($code, $text, $file, $line)
{
$this->head = 'Призошла ошибка и выброшено исключение';
$this->file = $file;
$this->line = $line;
throw new Error($text, $code);
}
public function exceptionHandler(Throwable $throwable)
{
$head = $this->head ?? 'Выброшено исключение';
$code = $throwable->getCode();
$text = $throwable->getMessage();
$file = $this->file ?? $throwable->getFile();
$line = $this->line ?? $throwable->getLine();
if ($code != 404) {
$code = 500;
}
http_response_code($code);
ob_end_clean();
if ($_SERVER['REMOTE_ADDR'] == '127.0.0.1' and DEBUG) {
require_once WWW . '/errors/development.php';
} else {
$log_date = date('d-m-Y');
$log_time = date('H:i:s');
$log_file = ROOT . "/tmp/logs/{$code}/{$log_date}.log";
if (isset($_SESSION['id'])) {
$log_user = 'Пользователь с id: ' . $_SESSION['id'];
} else {
$log_user = 'Гость с ip: ' . $_SERVER['REMOTE_ADDR'];
}
$log_text = "[{$log_time} - {$head}]\n{$code} | {$text} | {$file} | {$line}\n> {$log_user} <\n::\n";
error_log($log_text, 3, $log_file);
require_once WWW . "/errors/{$code}.html";
}
die();
}
}