willy.club/app/WillySoft/Http/ErrorHandler.php

54 lines
1.5 KiB
PHP
Raw Normal View History

2022-11-29 12:49:29 +00:00
<?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(self::error(...));
set_exception_handler(self::exception(...));
register_shutdown_function(self::shutdown(...), $callback);
}
private static function error($errno, $errstr, $errfile, $errline)
{
$errstr = htmlspecialchars($errstr);
self::$error_messages[] = "<b>Error[$errno]:</b> $errstr in <b>$errfile</b> at line <b>$errline</b>";
}
private static function exception($exception)
{
self::$error_messages[] = "<b>Uncaught Exception:</b> " . $exception;
}
private static function shutdown(callable $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);
}
}