2022-11-29 12:49:29 +00:00
|
|
|
<?php
|
|
|
|
|
|
|
|
namespace WillySoft\Http;
|
|
|
|
|
2023-01-29 12:35:00 +00:00
|
|
|
abstract class ErrorHandler {
|
2022-11-29 12:49:29 +00:00
|
|
|
private static array $error_messages = [];
|
|
|
|
|
|
|
|
/**
|
2023-01-29 12:35:00 +00:00
|
|
|
* On error or exception erase the output buffer then hand the errors as an array of HTML formatted messages to the callback
|
2022-11-29 12:49:29 +00:00
|
|
|
*/
|
2023-01-29 12:35:00 +00:00
|
|
|
static function register(callable $callback) {
|
2022-11-29 12:49:29 +00:00
|
|
|
ob_start();
|
|
|
|
|
2022-12-16 09:03:08 +00:00
|
|
|
set_error_handler(function($errno, $errstr, $errfile, $errline) {
|
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);
|
|
|
|
self::$error_messages[] = "<b>Error[$errno]:</b> $errstr in <b>$errfile</b> at line <b>$errline</b>";
|
|
|
|
});
|
2022-11-29 12:49:29 +00:00
|
|
|
|
2022-12-16 09:03:08 +00:00
|
|
|
set_exception_handler(function($exception) {
|
2023-01-29 12:35:00 +00:00
|
|
|
error_log("Uncaught Exception: $exception\n");
|
|
|
|
self::$error_messages[] = "<b>Uncaught Exception:</b> {$exception}";
|
2022-12-16 09:03:08 +00:00
|
|
|
});
|
2022-11-29 12:49:29 +00:00
|
|
|
|
2022-12-16 09:03:08 +00:00
|
|
|
register_shutdown_function(function() use(&$callback) {
|
|
|
|
if (!self::$error_messages) {
|
2022-12-16 09:05:19 +00:00
|
|
|
return;
|
2022-12-16 09:03:08 +00:00
|
|
|
}
|
2022-11-29 12:49:29 +00:00
|
|
|
|
2022-12-16 09:03:08 +00:00
|
|
|
ob_end_clean();
|
2022-11-29 12:49:29 +00:00
|
|
|
|
2022-12-16 09:03:08 +00:00
|
|
|
http_response_code(500);
|
|
|
|
header_remove();
|
2022-11-29 12:49:29 +00:00
|
|
|
|
2022-12-16 09:03:08 +00:00
|
|
|
$callback(self::$error_messages);
|
|
|
|
});
|
2022-11-29 12:49:29 +00:00
|
|
|
}
|
|
|
|
}
|