src/EventListener/ExceptionListener.php line 64
<?php
/**
* Created by PhpStorm.
* User: FogaPC
* Date: 12/02/2018
* Time: 20:52
*/
namespace App\EventListener;
use App\Entity\RegistroAttivita;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\ORM\ORMException;
use Psr\Log\LoggerInterface;;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Twig\Environment;
class ExceptionListener
{
protected $twig;
protected $doctrine;
protected $logger;
protected $env;
public function __construct(Environment $_twig, Registry $_doctrine, LoggerInterface $_logger, $_env)
{
$this->twig = $_twig;
$this->doctrine = $_doctrine;
$this->logger = $_logger;
$this->env = $_env;
return $this;
}
function ScriviRegistroAttivita($ip, $debug, $esito, $messaggio, $utente)
{
try {
$em = $this->doctrine->getManager();
$registro = new RegistroAttivita();
$registro->setData(new \DateTime('now'));
$registro->setClientIp($ip);
$registro->setDebug($debug);
$registro->setEsito($esito);
$registro->setMessaggio($messaggio);
$registro->setUtente($utente);
if (!$em->isOpen()) {
$this->entityManager = $em->create(
$em->getConnection(),
$em->getConfiguration()
);
}
$em->persist($registro);
$em->flush();
}catch (ORMException $ex){
$this->logger->critical("Errore inserimento registro attività --- " . $messaggio);
}catch (\Exception $ex){
$this->logger->critical("Errore inserimento registro attività --- " . $messaggio);
}
}
public function onKernelException(ExceptionEvent $event)
{
if ($this->env != "dev") {
// You get the exception object from the received event
$exception = $event->getThrowable();
$message = sprintf(
'My Error says: %s with code: %s',
$exception->getMessage(),
$exception->getCode()
);
// Customize your response object to display the exception details
$response = new Response();
//$response->setContent($message);
$response->setContent($this->twig->render('ZZ_front_end/pagina_errore/errore.html.twig'));
$registro = "Errore carico pagina<br>Carico pagina: " . $event->getRequest()->getSchemeAndHttpHost() . $event->getRequest()->getRequestUri() . "<br>Linea: " . $exception->getLine() . "<br>Eccezione: " . $exception->getCode() . " - " . $exception->getMessage() . "<br>" . "Trace: " . str_replace("\n", "<br>", $exception->getTraceAsString());
$this->ScriviRegistroAttivita($event->getRequest()->getClientIp(), $exception->getTraceAsString(), false, $registro, null);
// HttpExceptionInterface is a special type of exception that
// holds status code and header details
if ($exception instanceof HttpExceptionInterface) {
$response->setStatusCode($exception->getStatusCode());
$response->headers->replace($exception->getHeaders());
} else {
$response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
}
// sends the modified response object to the event
$event->setResponse($response);
}
}
}