<?php
declare(strict_types=1);
namespace App\EventSubscriber;
use App\DTO\Response\ErrorValidationApi\ErrorValidationApiDTO;
use App\Exception\ErrorValidationException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Serializer\SerializerInterface;
class ExceptionSubscriber implements EventSubscriberInterface
{
public function __construct(
private SerializerInterface $serializer,
) {
}
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => 'onKernelException',
];
}
public function onKernelException(ExceptionEvent $event): void
{
$exception = $event->getThrowable();
$urlPath = $event->getRequest()->getPathInfo();
if (str_starts_with($urlPath, '/api/')) {
// Обработка ошибок валидации для API
if ($exception instanceof ErrorValidationException) {
$responseDto = ErrorValidationApiDTO::createFromViolationList(
violations: $exception->violations,
messages: $exception->customErrorMessages,
);
$json = $this->serializer->serialize($responseDto, 'json');
$event->setResponse(new JsonResponse(data: $json, status: 400, json: true));
return;
}
}
}
}