src/EventListener/ApiIframeExceptionListener.php line 10

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpFoundation\JsonResponse;
  4. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  5. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  6. class ApiIframeExceptionListener
  7. {
  8.     public function onKernelException(ExceptionEvent $event)
  9.     {
  10.         $exception $event->getThrowable();
  11.         // Check if the request is coming from your REST API controllers
  12.         if (strpos($event->getRequest()->attributes->get('_route'),'api_iframe') !== false) {
  13.                 // Handle exceptions for your API controllers
  14.                 $response $this->handleApiException($exception);
  15.                 $event->setResponse($response);
  16.             }
  17.         }
  18.         private function handleApiException($exception)
  19.         {
  20.             $statusCode = ($exception instanceof HttpExceptionInterface) ? $exception->getStatusCode() : 500;
  21.             $response = [
  22.                 'error' => [
  23.                     'code' => $exception,
  24.                     'message' => $exception->getMessage(),
  25.                 ],
  26.             ];
  27.             return new JsonResponse($response$statusCode);
  28.         }
  29. }