src/EventListener/UnauthorizedExecptionListener.php line 14

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
  6. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  7. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  8. class UnauthorizedExecptionListener
  9. {
  10.     public function onKernelException(ExceptionEvent $event)
  11.     {
  12.         $request $event->getRequest();
  13.         $format $request->getRequestFormat();
  14.         $exception $event->getThrowable();
  15.         if ('json' !== $format || (!$exception instanceof AuthenticationException && !$exception instanceof AccessDeniedException) || !$exception instanceof UnauthorizedHttpException) {
  16.             return;
  17.         }
  18.         $response = new JsonResponse($exception->getMessage(), $exception->getCode());
  19.         $event->setResponse($response);
  20.         $event->stopPropagation();
  21.     }
  22. }