willy.club/app/WillySoft/ErrorHandler.php

38 lines
1.1 KiB
PHP

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