<?php
namespace App\EventListener;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
class UnauthorizedExecptionListener
{
public function onKernelException(ExceptionEvent $event)
{
$request = $event->getRequest();
$format = $request->getRequestFormat();
$exception = $event->getThrowable();
if ('json' !== $format || (!$exception instanceof AuthenticationException && !$exception instanceof AccessDeniedException) || !$exception instanceof UnauthorizedHttpException) {
return;
}
$response = new JsonResponse($exception->getMessage(), $exception->getCode());
$event->setResponse($response);
$event->stopPropagation();
}
}