src/EventListener/ApiExceptionSubscriber.php line 34

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use App\Exception\JsonSimpleMessageException;
  4. use App\Exception\SimpleMessageException;
  5. use Psr\Container\ContainerInterface;
  6. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpKernel\KernelEvents;
  10. class ApiExceptionSubscriber implements EventSubscriberInterface
  11. {
  12.     /**
  13.      * @var ContainerInterface
  14.      */
  15.     private $container;
  16.     
  17.     public function __construct(ContainerInterface $container)
  18.     {
  19.         $this->container $container;
  20.     }
  21.     
  22.     public static function getSubscribedEvents()
  23.     {
  24.         return array(
  25.             KernelEvents::EXCEPTION => 'onKernelException'
  26.         );
  27.     }
  28.     
  29.     public function onKernelException(ExceptionEvent $event)
  30.     {
  31.         $e $event->getThrowable();
  32.         if (!$e instanceof JsonSimpleMessageException) {
  33.             return;
  34.         }
  35.         
  36.         $exceptionCode =  $e->getCode() ? $e->getCode() : 500;
  37.         $error = array(
  38.             'error' => $e->getMessage(),
  39.             'code' => $exceptionCode,
  40.             'message' => $e->getMessage(),
  41.         );
  42.         $response = new JsonResponse(
  43.            $error,
  44.             $exceptionCode
  45.         );
  46.         $response->headers->set('Content-Type''application/problem+json');
  47.         $event->setResponse($response);
  48.     }
  49. }