src/System/Exception/Listener/ExceptionListener.php line 39

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\System\Exception\Listener;
  4. use ApiPlatform\Core\Bridge\Symfony\Validator\Exception\ValidationException;
  5. use ApiPlatform\Core\Exception\ItemNotFoundException;
  6. use App\Infrastructure\Interfaces\Logger\MessageDirectorInterface;
  7. use App\Infrastructure\Interfaces\Logger\NetworkLoggerInterface;
  8. use App\System\Infrastructure\Implementation\ApiException\ApiException;
  9. use App\System\Infrastructure\Implementation\Logger\Exceptions\ExceptionBuilder;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpFoundation\JsonResponse;
  12. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  13. use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
  14. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  15. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  16. use Symfony\Component\HttpKernel\KernelEvents;
  17. use Symfony\Component\Serializer\SerializerInterface;
  18. class ExceptionListener implements EventSubscriberInterface
  19. {
  20.     private const EXCLUDED_EXCEPTIONS = [
  21.         ValidationException::class,
  22.         NotFoundHttpException::class,
  23.         ItemNotFoundException::class,
  24.         AccessDeniedHttpException::class,
  25.         ApiException::class,
  26.     ];
  27.     public function __construct(
  28.         private readonly NetworkLoggerInterface $networkLogger,
  29.         private readonly MessageDirectorInterface $messageDirector,
  30.         private readonly SerializerInterface $serializer,
  31.     ) {
  32.     }
  33.     public function onKernelException(ExceptionEvent $event)
  34.     {
  35.         $exception $event->getThrowable();
  36.         if (!in_array(get_class($exception), self::EXCLUDED_EXCEPTIONS)) {
  37.             $builder = new ExceptionBuilder();
  38.             $builder->setException($exception);
  39.             $this->messageDirector->setMessageBuilder($builder);
  40.             $this->networkLogger->publish($this->messageDirector);
  41.         }
  42.         $httpCode 500;
  43.         if ($exception instanceof HttpExceptionInterface) {
  44.             $httpCode $exception->getStatusCode();
  45.         }
  46.         if ($exception instanceof ApiException) {
  47.             $httpCode $exception->getCode();
  48.         }
  49.         $msg $this->serializer->serialize($exception'json');
  50.         $event->setResponse(new JsonResponse($msg$httpCodejsontrue));
  51.     }
  52.     public static function getSubscribedEvents(): array
  53.     {
  54.         return [
  55.             KernelEvents::EXCEPTION => 'onKernelException',
  56.         ];
  57.     }
  58. }