src/EventSubscriber/ExceptionSubscriber.php line 56

Open in your IDE?
  1. <?php
  2. /**
  3.  * Created by IntelliJ IDEA.
  4.  * User: dogukan
  5.  * Date: 2019-01-24
  6.  * Time: 21:24
  7.  */
  8. namespace App\EventSubscriber;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpFoundation\JsonResponse;
  11. use Symfony\Component\HttpFoundation\Response;
  12. use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
  13. use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
  14. use Symfony\Component\HttpKernel\KernelEvents;
  15. use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
  16. use Symfony\Component\Security\Core\Exception\ExceptionInterface as SecurityCoreExceptionInterface;
  17. use Symfony\Component\Serializer\SerializerInterface;
  18. /**
  19.  * Class ExceptionSubscriber
  20.  * @package App\EventSubscriber
  21.  */
  22. class ExceptionSubscriber implements EventSubscriberInterface
  23. {
  24.     /**
  25.      * @var SerializerInterface
  26.      */
  27.     private $serializer;
  28.     /**
  29.      * ExceptionSubscriber constructor.
  30.      * @param SerializerInterface $serializer
  31.      */
  32.     public function __construct(SerializerInterface $serializer)
  33.     {
  34.         $this->serializer $serializer;
  35.     }
  36.     /**
  37.      * {@inheritdoc}
  38.      */
  39.     public static function getSubscribedEvents()
  40.     {
  41.         return [
  42.             KernelEvents::EXCEPTION => [
  43.                 ['processException'10]
  44.             ]
  45.         ];
  46.     }
  47.     /**
  48.      * @param GetResponseForExceptionEvent $event
  49.      */
  50.     public function processException(GetResponseForExceptionEvent $event)
  51.     {
  52.         $statusCode Response::HTTP_INTERNAL_SERVER_ERROR;
  53.         $headers = [];
  54.         $exception $event->getException();
  55.         if($exception instanceof HttpExceptionInterface) {
  56.             $statusCode $exception->getStatusCode();
  57.             $headers $exception->getHeaders();
  58.         }
  59.         else if($exception instanceof SecurityCoreExceptionInterface) {
  60.             if($exception->getCode() >= 400) {
  61.                 $statusCode $exception->getCode();
  62.             }
  63.             else if($exception instanceof AuthenticationCredentialsNotFoundException) {
  64.                 $statusCode Response::HTTP_UNAUTHORIZED;
  65.             }
  66.         }
  67.         $response = new JsonResponse(
  68.             [ 'error' => $this->serializer->normalize($exception'json') ],
  69.             $statusCode,
  70.             $headers
  71.         );
  72.         $event->setResponse($response);
  73.     }
  74. }