src/EventListener/Api/ApiExceptionListener.php line 21

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\EventListener\Api;
  4. use App\Service\EnvironmentService;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. class ApiExceptionListener
  9. {
  10.     protected EnvironmentService $environmentService;
  11.     public function __construct(EnvironmentService $environmentService)
  12.     {
  13.         $this->environmentService $environmentService;
  14.     }
  15.     public function onKernelException(ExceptionEvent $event): void
  16.     {
  17.         if (!$this->environmentService->isApi()) {
  18.             return;
  19.         }
  20.         $event->setResponse(
  21.             new JsonResponse(
  22.                 [
  23.                     'code' => 'Bad request',
  24.                     'message' => Response::HTTP_BAD_REQUEST,
  25.                 ],
  26.                 Response::HTTP_BAD_REQUEST
  27.             )
  28.         );
  29.     }
  30. }