<?php
namespace App\EventListener;
use App\Exception\APIBadRequestHttpException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Validator\ConstraintViolationInterface;
class ApiExceptionListener
{
public function onKernelException(ExceptionEvent $exceptionEvent)
{
$event = $exceptionEvent->getException();
if (!$event instanceof APIBadRequestHttpException) {
return;
}
$violationsArray = [];
if ($event->getViolations()) {
foreach ($event->getViolations() as $violation) {
/** @var ConstraintViolationInterface $violation */
$violationsArray[] = [
$violation->getPropertyPath() => $violation->getMessage()
];
}
}
$responseArray = [
'message' => $event->getMessage(),
'violations' => $violationsArray,
'code' => $event->getCode()
];
$response = new JsonResponse(
$responseArray,
$event->getCode()
);
$exceptionEvent->setResponse($response);
}
}