src/EventListener/ExceptionSubscriber.php line 36

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Twig\Environment;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpKernel\KernelEvents;
  6. use Symfony\Component\HttpKernel\Event\ExceptionEvent;
  7. use Symfony\Component\Security\Core\User\UserInterface;
  8. use Symfony\Component\DependencyInjection\ContainerInterface;
  9. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  10. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  11. class ExceptionSubscriber implements EventSubscriberInterface
  12. {
  13. private $user;
  14. private $twig;
  15. private $container;
  16. public function __construct(Environment $twig, ContainerInterface $container, UserInterface $user = null)
  17. {
  18. $this->user = $user;
  19. $this->twig = $twig;
  20. $this->container = $container;
  21. }
  22. public static function getSubscribedEvents()
  23. {
  24. return [
  25. KernelEvents::EXCEPTION => [
  26. ['onKernelException', 10]
  27. ]
  28. ];
  29. }
  30. public function onKernelException(ExceptionEvent $event)
  31. {
  32. // We only need to suppress errors in production environment
  33. if ($this->container->get('kernel')->getEnvironment() != 'prod') {
  34. return;
  35. }
  36. // @TODO: We need to take into account the response type as well (html, xml, json)
  37. $exception = method_exists($event, 'getThrowable') ? $event->getThrowable() : $event->getException();
  38. if ($exception->getCode() == 403) {
  39. // On forbidden exception, we need to either:
  40. // a) If user session is set, display forbidden page
  41. // b) If user session is not set, redirect to login page
  42. if (!empty($this->container->get('security.token_storage')->getToken()->getUser()) && $this->container->get('security.token_storage')->getToken()->getUser() != "anon.") {
  43. $template = $this->twig->render('errors/error.html.twig', [
  44. 'code' => 403,
  45. 'message' => 'Access Forbidden',
  46. 'description' => 'You are not authorized to access this page.',
  47. ]);
  48. $event->setResponse(new Response($template, 403));
  49. }
  50. } else {
  51. if ($exception instanceof NotFoundHttpException || $exception->getCode() == 404) {
  52. $template = $this->twig->render('errors/error.html.twig', [
  53. 'code' => 404,
  54. 'message' => 'Page not Found',
  55. 'description' => 'We were not able to find the page you are looking for.',
  56. ]);
  57. $event->setResponse(new Response($template, 404));
  58. } else {
  59. $template = $this->twig->render('errors/error.html.twig', [
  60. 'message' => 'Internal Server Error',
  61. 'code' => 500,
  62. 'description' => 'Something has gone wrong on the server. Please try again later.',
  63. ]);
  64. $event->setResponse(new Response($template, 500));
  65. }
  66. }
  67. }
  68. }