ErrorHandler
The ErrorHandler class provides centralized handling of PHP errors, exceptions, and fatal errors. It is responsible for generating meaningful error responses during runtime, supporting both full-page and JSON (AJAX/wire) modes.
Purpose
This class ensures that unexpected failures during the application's lifecycle are properly handled and displayed. It leverages PHP’s native set_exception_handler, set_error_handler, and register_shutdown_function to catch and respond to issues in real time.
Static Properties
static string $content: Holds the final error content to be rendered or returned as a response.
Key Methods
registerHandlers(): Registers all error/exception/shutdown handlers.checkFatalError(): Checks for fatal errors on shutdown and handles them accordingly.modifyOutputLayoutForError($contentToAdd): Outputs error layout with given content. Supports JSON or full HTML responses.
Output Handling
When a critical error is detected, the output is controlled via modifyOutputLayoutForError. It checks for a custom error layout at APP_PATH/error.php and loads it inside the layout file if available.
Important Note on Output Buffering
if (ob_get_level()) {
ob_end_clean();
}
If you want to see the output before the error occurred (for debugging), simply comment out or remove the ob_end_clean() line.
AJAX & Wire Mode
When handling AJAX or wire requests, the class returns a JSON response in the format:
{
"success": false,
"error": "Fatal Error: message in file on line"
}
Usage
1. Registering the Error Handlers
<?php
use Lib\ErrorHandler;
ErrorHandler::registerHandlers();
?>
2. Checking Fatal Errors Manually
<?php
use Lib\ErrorHandler;
ErrorHandler::checkFatalError();
?>
Note: The methods ErrorHandler::registerHandlers() and ErrorHandler::checkFatalError() are automatically invoked in the bootstrap.php file, so manual calls are typically unnecessary.
Error Handling
<?php use Lib\ErrorHandler; ?>
<div class="flex items-center justify-center h-screen">
<div class="text-center max-w-md">
<h1 class="text-6xl font-bold text-red-500">Oops!</h1>
<p class="text-xl mt-4"><?= ErrorHandler::$content ?></p>
<div class="mt-6">
<a href="/" class="px-6 py-3 text-lg font-semibold bg-red-500 hover:bg-red-600 rounded-lg shadow-md">Go Back Home</a>
</div>
</div>
</div>
For complete implementation, refer to src/Lib/ErrorHandler.php.