WizdomWeb/app/Utils/ErrorHandler.php

86 lines
2.6 KiB
PHP

<?php
namespace WizdomNetworks\WizeWeb\Utils;
use WizdomNetworks\WizeWeb\Utils\Logger;
/**
* ErrorHandler Utility
*
* A utility for handling errors and exceptions globally.
*
* Automatically logs errors and exceptions using the Logger utility and displays generic error messages to users.
*/
class ErrorHandler
{
/**
* Registers the custom error and exception handlers.
*/
public static function register(): void
{
set_error_handler([self::class, 'handleError']);
set_exception_handler([self::class, 'exception']);
Logger::info("ErrorHandler registered successfully.");
}
/**
* Custom error handler.
*
* Logs the error details and displays a generic error message.
*
* @param int $errno The error level.
* @param string $errstr The error message.
* @param string $errfile The file where the error occurred.
* @param int $errline The line number where the error occurred.
*/
public static function handleError(int $errno, string $errstr, string $errfile, int $errline): void
{
$message = "Error [$errno]: $errstr in $errfile on line $errline";
Logger::error($message);
http_response_code(500);
echo "An internal error occurred. Please try again later.";
exit;
}
/**
* Custom exception handler.
*
* Logs the exception details and displays a generic error message.
*
* @param \Throwable $exception The exception object.
*/
public static function exception(\Throwable $exception): void
{
$message = sprintf(
"Exception: %s in %s on line %d\nStack trace:\n%s",
$exception->getMessage(),
$exception->getFile(),
$exception->getLine(),
$exception->getTraceAsString()
);
Logger::error($message);
http_response_code(500);
echo "An internal error occurred. Please try again later.";
exit;
}
/**
* Handles fatal errors and shuts down the application gracefully.
*/
public static function shutdown(): void
{
$error = error_get_last();
if ($error && in_array($error['type'], [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE])) {
$message = sprintf(
"Fatal Error: %s in %s on line %d",
$error['message'],
$error['file'],
$error['line']
);
Logger::error($message);
http_response_code(500);
echo "A critical error occurred. Please contact support.";
}
}
}