<?php
namespace App\Service\Listeners;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\Serializer\SerializerInterface;
class ExceptionListener
{
private SerializerInterface $serializer;
public function __construct(SerializerInterface $serializer)
{
$this->serializer = $serializer;
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
// HttpException için özel mesaj belirleme
if ($exception instanceof HttpExceptionInterface) {
$message = $exception->getStatusCode() === Response::HTTP_REQUEST_ENTITY_TOO_LARGE
? 'The file size is too large. Please upload a smaller file.'
: $exception->getMessage();
$statusCode = $exception->getStatusCode();
} else {
// Diğer tüm beklenmeyen hatalar için
$message = 'An unexpected error occurred.';
$statusCode = Response::HTTP_INTERNAL_SERVER_ERROR;
}
// Hata yanıtı JSON olarak hazırlanır
$data = [
"message" => $message,
"severity" => "error",
"reportable" => $this->getDetailedErrorData($exception)
];
// JSON formatında hata yanıtı oluşturulur
$json = $this->serializer->serialize($data, 'json', [
'json_encode_options' => JsonResponse::DEFAULT_ENCODING_OPTIONS
]);
// Yanıt nesnesi oluşturulur ve etkinleştirilir
$response = new JsonResponse($json, $statusCode, [], true);
// $event->setResponse($response);
}
private function getDetailedErrorData(\Throwable $exception): array
{
return [
"message" => $exception->getMessage(),
// "trace" => $exception->getTrace(),
"file" => $exception->getFile(),
"code" => $exception->getCode(),
"line" => $exception->getLine(),
"trace_as_string" => $this->parseErrorReportFromString($exception->getTraceAsString())
];
}
function parseErrorReportFromString(string $errorString): string {
// Explode the string by "\n" to process each trace line individually
$lines = explode("\\n", $errorString);
$parsedReport = "Error Trace Report:\n\n";
foreach ($lines as $lineNumber => $line) {
// Use regex to capture file path, line number, and function call details
if (preg_match('/^(.*?)\((\d+)\): (.*)$/', stripslashes($line), $matches)) {
$filePath = $matches[1];
$lineNumber = $matches[2];
$functionCall = $matches[3];
// Append parsed information to the report
$parsedReport .= "File: $filePath\n";
$parsedReport .= "Line: $lineNumber\n";
$parsedReport .= "Function Call: $functionCall\n\n";
} else {
$parsedReport .= "Other Info: " . stripslashes($line) . "\n";
}
}
return $parsedReport;
}
}