src/Subscriber/ExceptionSubscriber.php line 41

Open in your IDE?
  1. <?php
  2. /**
  3.  * User: Mykola Zots
  4.  * Date: 2025-09-12
  5.  * Time: 08:42
  6.  */
  7. namespace App\Subscriber;
  8. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  9. use Symfony\Component\HttpFoundation\JsonResponse;
  10. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  11. use Symfony\Component\HttpKernel\KernelEvents;
  12. use Symfony\Component\HttpFoundation\RedirectResponse;
  13. use Symfony\Component\HttpFoundation\RequestStack;
  14. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  15. use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
  16. use Symfony\Component\HttpFoundation\Session\Flash\FlashBagInterface;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. class ExceptionSubscriber implements EventSubscriberInterface
  19. {
  20.     private $requestStack;
  21.     private $urlGenerator;
  22.     private $flashBag;
  23.     private $translator;
  24.     public function __construct(RequestStack $requestStackUrlGeneratorInterface $urlGenerator,TranslatorInterface $translatorFlashBagInterface $flashBag) {
  25.         $this->urlGenerator=$urlGenerator;
  26.         $this->requestStack=$requestStack;
  27.         $this->flashBag=$flashBag;
  28.         $this->translator=$translator;
  29.     }
  30.     
  31.     public static function getSubscribedEvents(): array
  32.     {
  33.         return [
  34.             KernelEvents::EXCEPTION => 'onKernelException',
  35.         ];
  36.     }
  37.     public function onKernelException(ExceptionEvent $event): void
  38.     {
  39.         $exception $event->getThrowable();
  40.         $request $event->getRequest();
  41.         
  42.         if ($exception instanceof \Symfony\Component\HttpKernel\Exception\BadRequestHttpException) {
  43.             
  44.              // Обмежимося адмінськими роутами (налаштуйте під себе)
  45.             $isAdmin str_starts_with((string) $request->attributes->get('_route'''), 'dashboard');
  46.             if ($isAdmin) {
  47.                 $this->flashBag->add('danger'$this->translator->trans($exception->getMessage()));
  48.                 
  49.                 $backUrl $request->headers->get('referer') ?$request->headers->get('referer'): $this->urlGenerator->generate('admin'); 
  50.                 $event->setResponse(new RedirectResponse($backUrl));
  51.             }else{
  52.                 $response = new JsonResponse([
  53.                     $exception->getMessage()
  54.                 ], 400);
  55.                 $event->setResponse($response);
  56.             }
  57.         }
  58.     }
  59. }