willy.club/app/WillySoft/Http/ErrorHandler.php
2022-12-16 10:05:19 +01:00

48 lines
1.4 KiB
PHP

<?php
namespace WillySoft\Http;
/**
* Captures errors and exceptions thrown by your application and renders them to the user
*/
abstract class ErrorHandler
{
/**
* Array of strings containing HTML error and exception messages
*/
private static array $error_messages = [];
/**
* Start capturing output to be replaced, set error and exception handlers and register shutdown function.
*
* On capturing an error or exception the callback will be called with an array of strings containing HTML error
* messages as an argument.
*/
public static function register(callable $callback)
{
ob_start();
set_error_handler(function($errno, $errstr, $errfile, $errline) {
$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) {
self::$error_messages[] = "<b>Uncaught Exception:</b> " . $exception;
});
register_shutdown_function(function() use(&$callback) {
if (!self::$error_messages) {
return;
}
// remove current output to be replaced by error page
ob_end_clean();
http_response_code(500);
header_remove();
$callback(self::$error_messages);
});
}
}