<?php
// src/EventListener/ExceptionListener.php
namespace App\EventListener;
use App\Services\Log\LogInteractionService;
use App\Utils\CommonFunctions;
use App\Utils\Exceptions\CustomException;
use App\Utils\Exceptions\NoPermitidoException;
use Logs\Entity\LogInteraction;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\EventListener\ExceptionListener;
class AnexoExceptionListener
{
private $logInteractionService;
public function __construct(LogInteractionService $logInteractionService)//,LogInteractionService $logInteractionService
{
$this->logInteractionService = $logInteractionService;
}
public function onKernelException(GetResponseForExceptionEvent $event )
{
// You get the exception object from the received event
$exception = $event->getException();
// Customize your response object to display the exception details
$response = new Response();
$response->setContent($exception->getMessage());
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
$this->logInteractionService->addLog(
LogInteraction::$ERROR,
'ExceptionListener',
null,
$exception->getMessage(),
CommonFunctions::getErrorException($exception)
);
switch (true){
case $exception instanceof AccessDeniedHttpException:
$message = "No tiene permisos para realizar la operaciĆ³n";
$code = 403;
break;
case $exception instanceof HttpExceptionInterface:
$message = $exception->getMessage();
$code = $exception->getStatusCode();
break;
case $exception instanceof NoPermitidoException:
case $exception instanceof CustomException:
case $exception->getCode()==500:
$message = $exception->getMessage();
$code = $exception->getCode();
break;
default:
$message = $exception->getMessage();
// $message = "Ha ocurrido un error";
$code = 500;
}
$response = new JsonResponse(['message' => $message],$code);
// sends the modified response object to the event
$event->setResponse($response);
}
}