Yes, Symfony offers the ability to handle exceptions. You must create an event listener that monitors the kernel.exception
event with high priority. Create an event handler as follows:
<?php namespace Acme\Bundle\MyBundle\EventListener; use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent; use Symfony\Component\HttpFoundation\JsonResponse; use Symfony\Component\Security\Core\Exception\AccessDeniedException; use Symfony\Component\Security\Core\Exception\AuthenticationException; class AjaxAuthenticationListener { public function onKernelException(GetResponseForExceptionEvent $event) { $request = $event->getRequest(); $format = $request->getRequestFormat(); $exception = $event->getException(); if ('json' !== $format || (!$exception instanceof AuthenticationException && !$exception instanceof AccessDeniedException)) { return; } $response = new JsonResponse($this->translator->trans($exception->getMessage()), $exception->getCode()); $event->setResponse($response); $event->stopPropagation(); } }
Now you need to register the event handler in one of your service.yml, for example:
kernel.listener.ajax_authentication_listener: class: Acme\Bundle\MyBundle\EventListener\AjaxAuthenticationListener tags: - { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 250 }
Note the priority
parameter used to tell Symfony to execute the handler before its own handlers, which have a lower priority.
And on your interface, you can register an event handler for jQuery, which reloads the page with such an error.
$(document).ready(function() { $(document).ajaxError(function (event, jqXHR) { if (403 === jqXHR.status) { window.location.reload(); } }); });
See this option for reference.
source share