src/ApiBundle/EventListener/ExceptionListener.php line 23

Open in your IDE?
  1. <?php
  2. namespace ApiBundle\EventListener;
  3. use ApiBundle\Api\Util\ExceptionUtil;
  4. use ApiBundle\ApiBundle;
  5. use ApiBundle\Viewer;
  6. use Symfony\Component\DependencyInjection\ContainerInterface;
  7. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  8. class ExceptionListener
  9. {
  10.     private $container;
  11.     
  12.     private $viewer;
  13.     public function __construct(ContainerInterface $containerViewer $viewer)
  14.     {
  15.         $this->container $container;
  16.         $this->viewer $viewer;
  17.     }
  18.     public function onKernelException(ExceptionEvent $event)
  19.     {
  20.         if (!$this->isApiPath($event->getRequest())) {
  21.             return;
  22.         }
  23.         $exception $event->getThrowable();
  24.         list($error$httpCode) = ExceptionUtil::getErrorAndHttpCodeFromException($exception$this->isDebug());
  25.         $error['message'] = $this->container->get('translator')->trans($error['message']);
  26.         $response $this->viewer->view(['error' => $error], $httpCode);
  27.         $event->setResponse($response);
  28.         $event->stopPropagation();
  29.     }
  30.     private function isApiPath($request)
  31.     {
  32.         return str_contains($request->getPathInfo(), ApiBundle::API_PREFIX);
  33.     }
  34.     private function isDebug()
  35.     {
  36.         return $this->container->get('kernel')->isDebug();
  37.     }
  38. }