<?php
declare(strict_types=1); namespace App\Http; use App\Exceptions\HttpException; use Throwable; class ErrorHandler { public static function handleException(Throwable $e): void { $statusCode = 500; $message = 'Internal Server Error'; $details = []; if ($e instanceof HttpException) { $statusCode = $e->getStatusCode(); $message = $e->getMessage(); $details = $e->getDetails(); } else { error_log('Unexpected Error: ' . $e->getMessage() . ' in ' . $e->getFile() . ' on line ' . $e->getLine()); } $response = [ 'error' => [ 'code' => $statusCode, 'message' => $message, 'details' => $details ] ]; if (!headers_sent()) { http_response_code($statusCode); header('Content-Type: application/json; charset=utf-8'); header('X-Content-Type-Options: nosniff'); header('X-Frame-Options: SAMEORIGIN'); header('X-XSS-Protection: 1; mode=block'); } echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); } public static function register(): void { set_exception_handler([self::class, 'handleException']); } } 