<?php
namespace GraphQL\EventListener;
use App\Exception\ValidationException;
use Eshop\Entity\Delivery\DeliverySlot;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\KernelInterface;
class ExceptionListener
{
private KernelInterface $kernel;
public function __construct(KernelInterface $kernel)
{
$this->kernel = $kernel;
}
public function __invoke(ExceptionEvent $event): void
{
//if($this->kernel->getEnvironment() !== 'prod') return;
$exception = $event->getThrowable();
$statusCode = $exception->getCode();
if ($exception instanceof ValidationException) {
$responseData = ['errors' => $exception->getErrors()];
$statusCode = 401;
} else if ($exception instanceof HttpException) {
$responseData = ['errors' => [$exception->getMessage()]];
$statusCode = $exception->getStatusCode();
} else {
$responseData = ['errors' => ['An error occurred']];
}
if($statusCode === 0) $statusCode = 500;
$response = new JsonResponse($responseData, $statusCode ?? 500);
$event->setResponse($response);
$event->stopPropagation();
}
}