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

48 lines
1.4 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();
2022-12-16 09:03:08 +00:00
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>";
});
2022-11-29 12:49:29 +00:00
2022-12-16 09:03:08 +00:00
set_exception_handler(function($exception) {
self::$error_messages[] = "<b>Uncaught Exception:</b> " . $exception;
});
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
// remove current output to be replaced by error page
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
}
}