willy.club/app/WillySoft/ErrorHandler.php

38 lines
1.1 KiB
PHP

<?php
namespace WillySoft;
abstract class ErrorHandler {
private static array $error_messages = [];
/**
* On error or exception erase the output buffer then hand the errors as an array of HTML formatted messages to the callback
*/
static function register(callable $callback) {
ob_start();
set_error_handler(function($errno, $errstr, $errfile, $errline) {
error_log("Error[$errno]: $errstr in $errfile at line $errline\n");
$errstr = htmlspecialchars($errstr);
self::$error_messages[] = "<b>Error[$errno]:</b> $errstr in <b>$errfile</b> at line <b>$errline</b>";
});
set_exception_handler(function($exception) {
error_log("Uncaught Exception: $exception\n");
self::$error_messages[] = "<b>Uncaught Exception:</b> {$exception}";
});
register_shutdown_function(function() use(&$callback) {
if (!self::$error_messages) {
return;
}
ob_end_clean();
http_response_code(500);
header_remove();
$callback(self::$error_messages);
});
}
}