willy.club/app/WillySoft/ErrorHandler.php

38 lines
1.1 KiB
PHP
Raw Normal View History

2022-11-29 12:49:29 +00:00
<?php
namespace WillySoft;
2022-11-29 12:49:29 +00:00
2023-02-03 11:00:13 +00:00
abstract class ErrorHandler
{
2022-11-29 12:49:29 +00:00
/**
2023-02-03 11:00:13 +00:00
* On error or exception erase the output buffer and hand the
* error message as an HTML formatted string to the callback
* then die
2022-11-29 12:49:29 +00:00
*/
2023-02-03 11:00:13 +00:00
static function register(callable $callback)
{
2022-11-29 12:49:29 +00:00
ob_start();
2023-02-03 11:00:13 +00:00
set_error_handler(function($errno, $errstr, $errfile, $errline) use (&$callback) {
2023-01-29 12:35:00 +00:00
error_log("Error[$errno]: $errstr in $errfile at line $errline\n");
2022-12-16 09:03:08 +00:00
$errstr = htmlspecialchars($errstr);
2023-02-03 11:00:13 +00:00
self::oof($callback, "<b>Error[$errno]:</b> $errstr in <b>$errfile</b> at line <b>$errline</b>");
2022-12-16 09:03:08 +00:00
});
2022-11-29 12:49:29 +00:00
2023-02-03 11:00:13 +00:00
set_exception_handler(function($exception) use (&$callback) {
2023-01-29 12:35:00 +00:00
error_log("Uncaught Exception: $exception\n");
2023-02-03 11:00:13 +00:00
self::oof($callback, "<b>Uncaught Exception:</b> {$exception}");
2022-12-16 09:03:08 +00:00
});
2023-02-03 11:00:13 +00:00
}
2022-11-29 12:49:29 +00:00
2023-02-03 11:00:13 +00:00
private static function oof(callable $callback, string $error_message)
{
ob_end_clean();
2022-11-29 12:49:29 +00:00
2023-02-03 11:00:13 +00:00
http_response_code(500);
header_remove();
2022-11-29 12:49:29 +00:00
2023-02-03 11:00:13 +00:00
$callback($error_message);
die();
2022-11-29 12:49:29 +00:00
}
}