<?php
declare(strict_types=1);
namespace App\Bundles\ApiBundle\EventSubscriber;
use App\Bundles\ApiBundle\v1\JsonResponse;
use App\Platform\Exception\ConstraintViolationException;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\KernelEvents;
class ExceptionSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents(): array
{
return [
KernelEvents::EXCEPTION => [
['onKernelException', 0],
],
];
}
public function onKernelException(ExceptionEvent $event): void
{
$throwable = $event->getThrowable();
if (!str_starts_with($event->getRequest()->getPathInfo(), '/api')) {
return;
}
if ($throwable instanceof ConstraintViolationException) {
$event->setResponse(JsonResponse::validationError($throwable->getErrors(), $throwable->getCode()));
}
if (!$throwable instanceof HttpExceptionInterface) {
return;
}
$event->setResponse(JsonResponse::error($throwable->getStatusCode(), $throwable->getMessage()));
}
}