src/EventListener/AppExceptionSubscriber.php line 23

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Model\Out\ExceptionOut;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpFoundation\JsonResponse;
  6. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  7. use Symfony\Component\HttpKernel\KernelEvents;
  8. class AppExceptionSubscriber implements EventSubscriberInterface
  9. {
  10.     /**
  11.      * @var string
  12.      */
  13.     private $env;
  14.     public function __construct(string $env)
  15.     {
  16.         $this->env $env;
  17.     }
  18.     public function onKernelException(GetResponseForExceptionEvent $event)
  19.     {
  20.         $path explode('/'$event->getRequest()->getPathInfo());
  21.         if ($path[1] !== 'api') return;
  22.         $out = new ExceptionOut($event->getException(), $this->env);
  23.         $response = new JsonResponse($out);
  24.         $response->headers->set('Content-Type''application/problem+json');
  25.         $event->setResponse($response);
  26.     }
  27.     public static function getSubscribedEvents()
  28.     {
  29.         return array(
  30.             KernelEvents::EXCEPTION => 'onKernelException'
  31.         );
  32.     }
  33. }