src/AppBundle/Event/GitHubCallExceptionListener.php line 39

Open in your IDE?
  1. <?php
  2. namespace AppBundle\Event;
  3. use AppBundle\Exception\GitHubCallException;
  4. use Symfony\Component\HttpFoundation\JsonResponse;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  8. use Symfony\Contracts\Translation\TranslatorInterface;
  9. use Twig\Environment;
  10. /**
  11.  * Class GitHubCallExceptionListener
  12.  * @package AppBundle\Event
  13.  */
  14. class GitHubCallExceptionListener
  15. {
  16.     /**
  17.      * @var Environment
  18.      */
  19.     private $twig;
  20.     /**
  21.      * @var TranslatorInterface
  22.      */
  23.     private $translator;
  24.     public function __construct(Environment $twigTranslatorInterface $translator)
  25.     {
  26.         $this->twig $twig;
  27.         $this->translator $translator;
  28.     }
  29.     /**
  30.      * @param ExceptionEvent $event
  31.      *
  32.      * @throws \Exception
  33.      */
  34.     public function onKernelException(ExceptionEvent $event): void
  35.     {
  36.         $exception $event->getThrowable();
  37.         if ($exception instanceof GitHubCallException) {
  38.             $httpCode $exception->getCode() ?? 500;
  39.             if (!$exception->isAjaxCall()) {
  40.                 $rendered $this->twig->render('@Twig/Exception/error.html.twig', [
  41.                     'errorDesc' => $this->translator->trans($exception->getMessage()),
  42.                     'httpCode' => $httpCode,
  43.                 ]);
  44.                 $event->setResponse(new Response($renderedResponse::HTTP_INTERNAL_SERVER_ERROR));
  45.             } else {
  46.                 $event->setResponse(new JsonResponse(['error' => true'errorDesc' => $this->translator->trans($exception->getMessage())]));
  47.             }
  48.         } elseif ($exception instanceof NotFoundHttpException) {
  49.             $httpCode $exception->getStatusCode();
  50.             $rendered $this->twig->render('@Twig/Exception/error.html.twig', [
  51.                 'errorDesc' => $this->translator->trans($exception->getMessage()),
  52.                 'httpCode' => $httpCode,
  53.             ]);
  54.             $event->setResponse(new Response($rendered$httpCode));
  55.         }
  56.     }
  57. }